简体   繁体   中英

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

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)?

This is probably not the best practice, but you can define the SWI-Prolog dynamic predicateportray/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM