程序代写代做代考 CSI2120 Programming Paradigms Jochen Lang

CSI2120 Programming Paradigms Jochen Lang
jlang@uottawa.ca
Faculté de génie | Faculty of Engineering
Jochen Lang, EECS jlang@uOttawa.ca

Logic Programming in Prolog
• Search Trees – voter
– farm buildings – negation
• Remark
– I use _ to distinguish free variables: X, _X, __X, ___X etc. – it may be easier to number: 􏰃 􏰄 􏰅 etc.
Jochen Lang, EECS jlang@uOttawa.ca

Example from slides
voter(Y) Y=X
name(X), citizen(X), adult(X)
name(joe).
name(jane).
citizen(jane).
citizen(joe).
adult(jane).
voter(X):-
name(X),
citizen(X),
adult(X).
?- voter(Y).
X=joe citizen(joe), adult(joe)
adult(joe)
X=jane citizen(jane), adult(jane)
adult(jane)
Jochen Lang, EECS jlang@uOttawa.ca

Example discussed on the board
Building categories:
parent(building,farmbuilding).
parent(farmbuilding,barn).
parent(farmbuilding,silo).
parent(farmbuilding,house).
parent(barn,horsebarn).
parent(barn,cowbarn).
typeof(X,Y):- parent(Z,X),typeof(Z,Y).
typeof(X,Y):- parent(Y,X).
?- typeof(cowbarn,A).
Jochen Lang, EECS jlang@uOttawa.ca

typeof(cowbarn, A)
X=cowbarn, Y=A
parent(Z,cowbarn),typeof(Z,A)
_______X=cowbarn, ______Y = A
parent( A, cowbarn)
A=barn
Z=barn
typeof(barn,A)
_X=barn, _Y = A
parent(_Z,barn),typeof(_Z,A)
_Z=farmbuilding
typeof(farmbuilding,A)
__X=farmbuidling, __Y = A
parent(__Z,farmbuilding),typeof(__Z,A)
__Z=building
typeof(building,A)
___X=building, __Y = A
______X=barn, _____Y = A
parent( A, barn)
A = farmbuilding
_____X=farmbuilding, ____Y = A
parent(A, farmbuilding)
____X=building, ___Y = A
A = building
Jochen Lang, EECS jlang@uOttawa.ca
parent(___Z,building),typeof(___Z,A)
parent(A, building)

Negation
• •

Negation is the not predicate
Negation is implemented as failure, recall the is_false example from the slides
not(P) :- P, !, fail.
not(P).
Search tree
– Negation succeeding
not(g(X))
P=g(X) P=g(X)
g(X), !, fail
• g(X) is false
– Negation failing • g(X) is true
not(g(X))
P=g(X) g(X), !, fail
fail
Jochen Lang, EECS jlang@uOttawa.ca

Example:
Liking a pet if not allergic
pet(dog).
pet(cat).
allergic(jane,cat).
allergic(joe,dog).
likes(N,X) :- pet(X),
\+allergic(N,X).
Example query: likes(jane,X).
Jochen Lang, EECS jlang@uOttawa.ca

N=jane _X=X
likes(jane,X)
_X=cat \+allergic(jane,cat)
allergic(jane,cat), !, fail fail
Example query:
?- likes(jane,X).
X = dog ;
false.
pet(_X),\+allergic(jane,_X) _X=dog
\+allergic(jane,dog) allergic(jane,dog), !, fail
Jochen Lang, EECS jlang@uOttawa.ca