CSCE 420 Lecture 19

From Notes
Jump to navigation Jump to search

« previous | Thursday, March 28, 2013 | next »


Prolog

Two flavors

  • GNU Prolog (gprolog)
  • SWI Prolog

Syntax

  • Expressions end in a period (.)
  • Variables start with an upper-case letter
  • Propositions start with lower-case letter
  • Implication is actually backwards: use :- as "implied by" operator.
  • Conjunction operator is a comma (,)
  • Disjunction cannot be expressed
dog(fido).
cat(felix).
bird(tweety).

author(moby_dick,melville).
author(shakespeare,hamlet).
country(melville,america).
country(shakespeare,england).


% (this is a comment)
% all birds fly == forall X bird(X) -> flies(X)

fly(X) :- bird(X).

book(X) :- author(B,_).

inanimate(X) :- \+ animal(X).

mammal(X) :- dog(X).
mammal(X) :- cat(X).
animal(X) :- bird(X).
animal(X) :- mammal(X).

british_author(X) :- author(_,X),country(X,england).

Running a File

Execute the gprolog command:

% gprolog

Load the prolog file

?- ['demo.pl'].

Make queries:

?- dog(fido).
Yes
 
?- dog(felix).
No

Ask questions by using variables

?- country(shakespeare,X).
X = england ; % semicolon is "show next if there is one
No

?- cat(C).
C = felix ;
No

?- flies(W).
W = tweety ;

?- mammal(X).
X = fido ;
X = felix ;
No

Arithmetic

% `is` only works if the RHS is bound
double(X,Y) :- \* var(X), Y is 2*X.
double(X,Y) :- var(X), X is 0.5*Y.
double(3,%).
Y = 6 ;
No

Practical Example

% gold members have over 100,000 frequent flyer miles
gold(X) :- frequent_flyer(X), miles(X,M), M>100000.

% definition of factorial
factorial(1,1).
factorial(X,Y) :- X>1, Z is X-1, factorial(Z,W), Y is X*W.

Wumpus World

row(1).
row(2).
row(3).
row(4).
col(1).
col(2).
col(3).
col(4).

room(X,Y) :- row(X),col(Y).

adjacent(X,Y,P,Q) :- room(X,Y) , P is X , Q is Y+1 , room(P,Q).
adjacent(X,Y,P,Q) :- room(X,Y) , P is X , Q is Y-1 , room(P,Q).
adjacent(X,Y,P,Q) :- room(X,Y) , P is X+1 , Q is Y , room(P,Q).
adjacent(X,Y,P,Q) :- room(X,Y) , P is X-1 , Q is Y , room(P,Q).

% BEGIN
% if we have knowledge about cave layout
pit(1,3).
pit(3,3).
pit(4,4).
wumpus(3,1).

breeze(X,Y) :- room(X,Y) , pit(P,Q) , adjacent(X,Y,P,Q).
stench(X,Y) :- room(X,Y) , wumpus(P,Q) , adjacent(X,Y,P,Q).
% END

% BEGIN
% if we do not have map

% start in room (1,1)
in(1,1).

% situation 2
% in(1,2).
% stench(2,1).
% visited(1,1).

% situation 3
% in(1,2).
% breeze(1,2).
% stench(2,1).
% visited(1,1).
% visited(2,1).

safe(X,Y) :- no_wumpus(X,Y) , no_pit(X,Y).

no_wumpus(X,Y) :- adjacent(X,Y,P,Q) , visited(P,Q) , not(stench(P,Q))
no_wumpus(X,Y) :- adjacent(X,Y,P,Q) , visited(P,Q) , not(breeze(P,Q))