程序代写代做代考 go database Programming Paradigms CSI2120

Programming Paradigms CSI2120
Jochen Lang
EECS, University of Ottawa Canada

Logic Programming in Prolog
• Advanced Examples
– Collecting solutions of a Goal – River crossing puzzle
CSI2120: Programming Paradigms

Built-in Predicates bagof/3 and setof/3
• bagof/3 finds all the solution and enters them in a list
• Example
grade(ana,5).
grade(heather,4).
grade(liz,5).
• Queries
?- bagof(N,grade(N,5),L). L=[ana,liz].
?- bagof([N,G],grade(N,G),L). L=[[ana,5],[heather,4],[liz,5]].
• setof/3 is similar but eliminates duplicates and sorts the result
CSI2120: Programming Paradigms

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).
• Queries
?- bagof(Z,bag(X,Y,Z),B).
?- bagof(Z,(bag(X,Y,Z),Z>2),B).
CSI2120: Programming Paradigms
• Not binding a variable in a goal with the 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: Street Turns
• Database: • Queries: turn(elgin,wellington). ?- setof(X,turn(X,Y),B).
turn(elgin,catherine).
turn(elgin,laurier).
turn(qed,laurier).
turn(qed,bank).
turn(bank,qed).
turn(bank,sommerset).
turn(bank,gladstone).
turn(bank,wellington).
?- setof(Y,turn(X,Y),B).
?- setof(Y,X^turn(X,Y),B).
?- bagof(Y,X^turn(X,Y),B).
?- setof([X,Y],turn(X,Y),B).
CSI2120: Programming Paradigms

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