11 Finding All Answers

11 Finding All Answers

You can collect all of the answers to a query using:
bagof(X,Q,L)
where X is a term made of the free variables in Q. This is true if L is a non-empty list of the X's for which Q is true. There is an element of L for each proof of Q. This fails if Q has no answers.
cilog: tell p(a,b).
cilog: tell p(b,c).
cilog: tell p(a,d).
cilog: tell p(e,f).
cilog: tell p(e,d).
cilog: ask bagof(X,p(a,X),L).
Answer: bagof(A, p(a, A), [b, d]).
Note that X can be any term. For example, you could ask for the list of pairs:
cilog: ask bagof(ppair(X,Y),p(X,Y),L).
Answer: bagof(ppair(A, B), p(A, B), [ppair(a, b), ppair(b, c), ppair(a, d), ppair(e, f), ppair(e, d)]).
Q can be any body. For example, continuing our example:
cilog: ask bagof(triple(X,Y,Z),p(X,Y)&p(Y,Z),L).
Answer: bagof(triple(A, B, C), p(A, B)&p(B, C), [triple(a, b, c)]).
Runtime since last report: 0 secs.
[ok,more,how,help]: ok.
cilog: tell p(c,e).
cilog: ask bagof(triple(X,Y,Z),p(X,Y)&p(Y,Z),L).
Answer: bagof(triple(A, B, C), p(A, B)&p(B, C),
[triple(a, b, c), triple(b, c, e), triple(c, e, f), triple(c, e, d)]).
Runtime since last report: 0 secs.
[ok,more,how,help]:
If Q contains a variable that doesn't appear in X, then this returns a list for each value that has a non-empty list of solutions. For example,
cilog: ask bagof(X,p(Y,X),L).
Answer: bagof(A, p(b, A), [c]).
Runtime since last report: 0 secs.
[ok,more,how,help]: more.
Answer: bagof(A, p(a, A), [b, d]).
Runtime since last report: 0 secs.
[ok,more,how,help]: more.
Answer: bagof(A, p(e, A), [f, d]).
Runtime since last report: 0 secs.
[ok,more,how,help]: more.
Answer: bagof(A, p(c, A), [e]).
Runtime since last report: 0 secs.
[ok,more,how,help]: more.
No more answers.
Runtime since last report: 0 secs.
cilog:
If you want to ask for the X's for which there exists a Y such that P(Y,X) (i.e., if you don't want an answer for each Y), you can use the operator V^Q which means "there exists a V such that Q is true". [Note that ^ is only defined in the context of bagof. It doesn't need to be used elsewhere.]
cilog: ask bagof(X,Y^p(Y,X),L).
Answer: bagof(A, B^p(B, A), [b, c, d, f, d, e]).
Runtime since last report: 0 secs.
[ok,more,how,help]: more.
No more answers.
Runtime since last report: 0 secs.
cilog:

©David Poole, 1998

 11 Finding All Answers