简体   繁体   中英

How to print a list in Prolog

I assert student details to DB like this.

assert(details(Age,Name,Dob,Zodiac)).

I want to get a details list sorted by Age(asending or desending) and display it somethin like this.

Name : sam
Date of Birth : 1991-8-1
Age : 23
Zodiac Sign : leo

Name : john
Date of Birth : 1993-6-12
Age : 25
Zodiac Sign : cancer

I tried with bagof,findall but could not get a correct answer. Please help me.

Thanks.

As far as ordering the facts, using setof would be helpful here, assuming your facts are all distinct in some way. setof will automatically sort by a natural order, which in this case, will be by the first argument in details , which is the age:

list_ascending :-
    detail_list(List),
    maplist(write_item, List).

list_descending :-
    detail_list(List),
    reverse(List, DescList),
    maplist(write_item, DescList).

detail_list(List) :-
    setof(details(Age,Name,Dob,Zodiac), details(Age,Name,Dob,Zodiac), List).

Then you just need to create your write_item predicate:

write_item(details(Age,Name,Dob,Zodiac)) :-
    write('Name : '), write(Name), nl,
    write('Date of Birth : '), write(Dob), nl,
    write('Age : '), write(Age), nl,
    write('Zodiac Sign : '), write(Zodiac), nl, nl.

Or, using, format :

write_item(details(Age,Name,Dob,Zodiac)) :-
    format('Name : ~w~NDate of Birth : ~w~NAge : ~w~NZodiac Sign : ~w~2N',
           [Name, Dob, Age, Zodiac]).

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