Prolog Cpt114 - Week 2

Post on 25-May-2015

456 views 0 download

Tags:

Transcript of Prolog Cpt114 - Week 2

Prolog Week 2

Objectives of this session All in prolog Instance and queries Anonymous Variable Arithmetic in Prolog Review A Family Tree

Complete Syntax of Terms

Term

Constant VariableCompound Term

Atom Numberalpha17gross_payjohn_smithdyspepsia+=/=’12Q&A’

01571.6182.04e-27-13.6

likes(john, mary)book(dickens, Z, cricket)f(x)[1, 3, g(a), 7, 9]-(+(15, 17), t)15 + 17 - t

XGross_payDiagnosis_257_

Names an individual Names an individualthat has parts

Stands for an individualunable to be named when program is written

All the prolog

Program consists of Facts Rules Goals

Facts

Rules

Goals

Instance and queries

Anonymous Variable

Arithmetics in Prolog

comparisons

arithmetic comparisons automatically evaluate expressions

X =:= Y X and Y must both be arithmetic expressions (no variables)

X =\= YX > Y ?- 12 =:= 6+6.X >= Y Yes X < YX =< Y ?- X =:= 6+6.

ERROR: Arguments are not sufficiently instantiated

Expr1 =:= Expr2 True if expression Expr1 evaluates to a number equal to Expr2.

User-defined perators

it is sometimes convenient to write functors/predicates as operators

predefined: +(2, 3) 2 + 3

user defined? likes(dave, cubs) dave likes cubs

Exersice

pam

bob liz

pat

jim

ann

Find:grandfathergrandmothergrandsongranddaughterbrothersister

tom

14

Recursive Rules: Predecessor Relation Some X is an indirect predecessor of some Z if

there is a partnership chain of people between X and Z.

X

Z

parent predecessor

X

Y1

parent

predecessor

Y2

parent

Z

parent

predecessor(X, Z) :- parent(X, Z).

predecessor(X, Z) :- parent(X, Y1), parent(Y1, Y2), parent(Y2, Z).

X is a direct predecessor of ZX is an indirect predecessor of Z

15

Recursive Rules: Predecessor Relation

Predecessor of any depth. Define predecessor relation in terms of itself.

For all X and ZX is a predecessor of Z ifthere is a Y such that (1) X is a parent of Y and(2) Y is a predecessor of Z.

predecessor(X, Z) :- parent(X, Z).

predecessor(X, Z) :- parent(X, Y), predecessor(Y, Z).

Recursive

16

Family Program

parent(pam, bob).parent(tom, bob).parent(tom, liz).parent(bob, ann).parent(bob, pat).parent(pat, jim).female(pam).female(liz).female(ann).female(pat).male(tom).male(bob).male(jim).

mother(X, Y) :- parent(X, Y), female(X).

sister(X, Y) :- parent(Z, X), parent(Z, Y), female(X).

a(g, h).a(g, d).a(e, d).a(h, f).a(e, f).a(a, e).a(a, b).a(b, f).a(b, c).a(f, c).

arc

a

ed

g h

f

cbpath(X, Y)=a(X,Y).path(X, Y) :- a(X, Z), path(Z, Y).

?- path(f, f).?- path(a, c).?- path(g, e).?- path(g, X).?- path(X, h).

arc

a

ed

g h

f

cb