arfarinha
arfarinha

Reputation: 172

How do you show the contents of a list in prolog?

I have the following code:

 born(person1,1991).

 born(person2,1965).

 born(person3,1966).

 born(person4,1967).

 born(person5,1968).

 born(person6,1969).


 criteria(X,Y):- born(X,Z) , born(Y,T) , Z<T.
 order([]).  

 order([X]).  

 order([X,Y|L]) :- criteria(X,Y),order([Y|L]). 

I have the predicate order([X,Y|L) that is true if the list is ordered , in this case, the first element should be the oldest person and the last element should be the youngest person.

My question is: how would you do a predicate print_List/1 that allows you to print the content of a list . An example of how it should work would be:

  ?-print_List([X]).
  X = [person2, person3, person4, person5, person6, person1)

Upvotes: 0

Views: 1581

Answers (2)

CapelliC
CapelliC

Reputation: 60034

Your code it's a bit unusual, it builds a list 'lazily'...

?- order(X), write(X).
[]
X = [] ;
[_G357]
X = [_G357] ;
[person2,person1]
X = [person2, person1] ;
[person2,person3]
X = [person2, person3] ;
[person2,person3,person1]
X = [person2, person3, person1] ;
[person2,person3,person4]
X = [person2, person3, person4] .
....

and then a 'all solutions' built in is required, but findall/3 applied to it gives:

?- findall(X,order(X),L).
L = [[], [_G1108], [person2, person1], [person2, person3], [person2, person3, person1], [person2, person3, person4], [person2, person3|...], [person2|...], [...|...]|...].

You could consider to shorten the code using more directly any of the 'all solutions' built ins.

Anyway, when write or format don't fit, I use maplist. Paired with library(lambda) you get control in a fairly compact way: for instance, to display your data sorted:

?- setof(Y-P, Y^P^born(P, Y), L), maplist(writeln, L).
1965-person2
1966-person3
1967-person4
1968-person5
1969-person6
1991-person1
L = [1965-person2, 1966-person3, 1967-person4, 1968-person5, 1969-person6, 1991-person1].

Here setof/3 build a list sorted on Year, then with lambda we can recover the field of interest.

?- setof(Y-P, Y^P^born(P, Y), L), maplist(\E^(E=(Y-P), writeln(P)), L).
person2
person3
person4
person5
person6
person1
L = [1965-person2, 1966-person3, 1967-person4, 1968-person5, 1969-person6, 1991-person1].

Upvotes: 2

LeleDumbo
LeleDumbo

Reputation: 9340

Shouldn't write/1 do? Your example doesn't seem to show a print behavior, so you could simply call order with the right parameter (ordered born, either manually or create another predicate to generate it) and the Prolog system should show the content of X.

Upvotes: 0

Related Questions