CIS 479/579 Prolog

 

 

 

 

 

 

Above graphical information is denoted as below:

 

parent (pam, bob).

parent (tom, bob).

parent (tom, liz).

parent (bob, ann).

parent (bob, pat).

parent (pat, jim).

 

In order to add an item to this fact base, use "assert"

To subtract, use "retract"

 

% a long way of defining "grandparent"

 

?-parent(y, jim), parent(x, y).

x = bob

y = pat

 

% this would be easier

 

grandparent(x, z) :- parent(x, y), parent(y, z).

?-grandparent(x, jim).

x = bob

% you could also do an inverse function

offspring(x, y) :- parent(y,x).            % this defines offspring as the inverse of parent

 

% you can also do unary relationships

female(pam).

male(tom).

male(bob).

female(liz).

female(pat).

female(ann).

male(jim).

 

% this combines functions

mother(x, y) :- parent(x, y), female(x).

offspring(x, y) :- mother(y, x).

 

% the following is an example of recursion in Prolog

ancestor(x, z) :- parent(x, z).

ancestor(x, z) :- parent(x, y), ancestor(y, z).

 

/* The first, shorter, expression is evaluated first, otherwise it may encounter an infinite

    loop. The second expression represents a recursive search, provided that the first

    condition is not met. */

 

% We will try this with a relationship that is not directly connected

 

?-ancestor(tom, jim)     % this fails the first search

 

% this is how the second search traces out

 

   ancestor(x, z) :- parent(x, y), ancestor(y, z).     % perform initial search against fact base

      x = tom    z = jim        x = tom  y = bob       y = bob   z = jim

 

% initial fails, (bob is not DIRECT ancestor of jim), so it proceeds to another search,

% picking up where it left off

 

    ancestor(x, z) :- parent(x, y), ancestor(y, z).    % bob, jim is from previous "ancestor"

        x = bob    z = jim          x = bob   y = pat       y = pat  z = jim

 

yes       % this is eventual output. for brevity, assume we went through the "bob, ann" 

            % relationship under parent(x, y)

 

% "not" is not defined in Prolog, this is how to define it

 

not(x) :- x, !, fail.

not(x).

course(cs101, smith, time(teus,3,5), loc(Cab, 2o3)).

when(cname, time) :- course(cname, _ , time, _).

?- when cs101, T)

T = time(tues, 3,5)

.(a, .(b, .(c, [ ] )))

[a, b, c]

[H. | T]

H= car T= cdr L= [a, b, c]

Tail = [b, c]

L = [a | Tail]

L = [a | [b,c]]

L = [a, b | [c]]

L = [a, b, c | [ ]]