How to print prolog list variable's output on separate lines?

Viewed 148

Initial code:

nutrition(fruits, NutritionList) :- 
        findall(Nutrition, fruitNutrition(Nutrition), NutritionList).

The problem with this is that it tries to print all nutritions on 1 single line whereas I want them on separate lines.

Got:

NutritionList = [a,b,c,d]; 

Wanted:

NutritionList = 
a 
b 
c
d 

Then I tried this method I found in another SO answer:

nutrition(fruits, NutritionList) :- 
            findall(Nutrition, fruitNutrition(Nutrition), NutritionList),
            maplist(writeln, NutritionList). 

But the problem with this is that it doesn't print the variable name at the top and also prints the output once on separate lines and once in the old way like:

a
b
c
d
NutritionList = [a,b,c,d]

How do I get the output in the format I want (under wanted in bold above)?

1 Answers

This is probably not the best practice, but you can define the SWI-Prolog dynamic predicate portray/1 to change the behaviour of the system when printing specific terms.

fruitNutrition(a).
fruitNutrition(b).
fruitNutrition(c).
fruitNutrition(d).

nutrition(fruits, mylist(NutritionList)) :-
   findall(Nutrition, fruitNutrition(Nutrition), NutritionList).

portray(mylist(List)) :- 
   nl, 
   maplist(writeln, List).

Examples:

?- nutrition(fruits, NutritionList).
NutritionList = 
a
b
c
d
.

?- nutrition(fruits, mylist(NutritionList)).
NutritionList = [a, b, c, d].

?- print([one, two, three]).
[one,two,three]
true.

?- print(mylist([one, two, three])).

one
two
three
true.

Related