2

Imagine my siblings, my cousins and me and our total count is 10. So i write this code and when i run it, it just give me 1 output. How can i print all the X values(names) on this query. And if possible how can i change what name comes first or how can i choose as a like what 3rd or 5th name would be ? (My granduncle is my grandfather's brother.)

Here is my code and output

granduncle(T,X) :- brother(T,Z),parent(Z,Y),parent(Y,X).


?- granduncle(john,X).
X=stan
false
  • 10,264
  • 13
  • 101
  • 209
Utku
  • 21
  • 3
  • Do you want a list oft all solutions, or do you want to enumerate solutions one by one? For the latter, try pressing ";" or "Space" or "n" after each answer. – Isabelle Newbie Jan 24 '21 at 10:27

1 Answers1

1

You need to use the collection predicates:

bagof/3 setof/3

and

findall/3

to collect all the solutions into a single list.

For example:

bagof(X,granduncle(john,X),Bag).

will create a list of solutions in Bag.

Then you can slice & dice the list with predicates like:

David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
  • And why not just `setof/3` in place of `bagof/3`? – false Jan 23 '21 at 10:29
  • @false It evidently depends on what you want to do. What if there are no duplicates? Then `bagof/3` - it will (probably) be faster by a couple of milliseconds (old habits grown on sub-10-MHz CPUs die hard) – David Tonhofer Jan 23 '21 at 10:34
  • 2
    As far as I remember SWI, its `setof/3` no longer depends on `bagof/3` and thus can easily be of same speed. Also `setof/3` hides the often varying order - even if you do not have redundant solutions. – false Jan 23 '21 at 10:40