Logic Programming in Prolog
• AdvancedExamples
– Collecting solutions of a Goal – River crossing puzzle
Copyright By PowCoder代写 加微信 powcoder
Built-in Predicates bagof/3 and setof/3
• bagof/3findsallthesolutionandenterstheminalist • Example
grade(ana,5).
grade(heather,4).
grade(liz,5).
?- bagof(N,grade(N,5),L).
L=[ana,liz].
?- bagof([N,G],grade(N,G),L).
L=[[ana,5],[heather,4],[liz,5]].
• setof/3issimilarbuteliminatesduplicatesandsortsthe result
http://cs.union.edu/~striegnk/learn-prolog-now/html/node95.html#sec.l11.collecting.sol
Example: Bag of Numbers
• Database
bag(2,4,1).
bag(3,5,2).
bag(7,8,2).
bag(4,3,1).
bag(5,2,4).
bag(2,1,4).
bag(2,2,4).
bag(7,3,5).
bag(7,3,3).
?- bagof(Z,bag(X,Y,Z),B).
?- bagof(Z,(bag(X,Y,Z),Z>2),B).
• Notbindingavariableinagoalwiththe existential operator ^
?- bagof(Z,X^bag(X,Y,Z),B).
?- setof(Z,X^bag(X,Y,Z),B).
?- bagof(Z,X^Y^bag(X,Y,Z),B).
• Not binding any variable in the goal (same as one line above).
?- findall(Z,bag(X,Y,Z),B).
Example: More grades
• Database
grade(nick,8).
grade(rachel,4).
grade(peter,3).
grade(monica,7).
grade(samantha,4).
• Queries:
?- setof(A,N^grade(N,A),B).
?- setof(A,N^grade(N,A),[H|T]).
?- setof(A,N^grade(N,A),[H|_]).
?- setof([A,N],grade(N,A),[[_,J]|_]). ?- grade(P,A1),\+((grade(_,A2),A2