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)?
CodePudding user response:
I did not run any of the following code to verify it works but it should. If not let me know and I will fix it.
This answer is derived from this post - Format/2,3 special sequence @ example
First use your nutrition/2 to get the nutrition list (NutritionList
).
nutrition(fruits, NutritionList) :-
findall(Nutrition, fruitNutrition(Nutrition), NutritionList).
In a separate predicate you can print the list using SWI-Prolog format with @
.
format_nutrition_list(NutritionList) :-
format('Nutrition List~n',[]),
format('~@',[print_list(NutritionList)]).
print_list([H|T]) :-
format('~k~n',[H]),
print_list(T).
print_list([]).
Putting it all together in one predicate.
nutrition(fruits) :-
findall(Nutrition, fruitNutrition(Nutrition), NutritionList),
format_nutrition_list(NutritionList).
nutrition/1 will not return NutritionList
. If you want the NutritionList
returned just use this as the head. However if you run it with NutritionList
being returned from the top level it will print the list out, which you didn't want.
nutrition(fruits,NutritionList) :-
...
And for the bonus answer round.
CodePudding user response:
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.