CS 152 - Lecture 20

Cover page image

Cay S. Horstmann

How Does Prolog Work?

Unification

Unification Algorithm

Unification Example

The Goal Stack

Choice Points

Variable Renaming

Summary of Prolog Algorithm

Lab

???

Step 1: Unification

  1. Consider the terms
    member(X, cons(john, cons(mary, nil)))
    member(X17, cons(X17, T))

    Compute a unifying substitution (by hand). What is it?

  2. Consider the goal
    member(X, cons(john, cons(mary, nil)))

    and the clause

    member(X, cons(X, T)) :- member(X,T).

    Compute a unifying substitution of the goal and the head of the clause after renaming variables in the clause. What is it?

  3. Apply the substitution to the body of the clause. What term do you get?

Step 2: How Prolog Works

Save this Prolog.scala file and load it into Eclipse.

Note these commands in Main.main:

import Prolog._
val member = new Predicate
member('X, 'X::'Xs)!
member('X, 'Y::'Ys) :- member('X, 'Ys)
member('X, 'john :: 'mary :: 'nil)?
more
more

As you can see, the implementor of this interpreter cleverly overloaded operators ! (fact), :- (provided that) and ? (query).

Note the single quote that is used for variables.

Now change Main.main to

...
showMatches = true
member('X, 'john :: 'mary :: 'nil)?
more
more

What output do you get?

Step 3: A Complete Trace

Now comes the hard part: Put together a complete trace of what the interpreter does. In each step, you can choose from

Use the same substitution that the Scala interpreter uses. When I ran it, the trace output started with

unify 'X with 'john = true
unify 'X16 with 'john = true
unify 'Xs17 with 'mary :: 'nil = true

My solution would be

Step 1. Push member(X, cons(john, cons(mary, nil))) on goal stack

Step 2. Choose rule member(X, cons(X, Xs)).

Step 3. Rename into member(X16, cons(X16, Xs17)).

Step 4. Use unification: X = X16, john = X16, Xs17 = cons(mary, nil) solves as X = john, X16 = john, Xs17 = cons(mary, nil).

Step 5. Unification with fact was success. Display result.

Step 6. Choose rule member(X, cons(Y, Ys)) :- member(X, Ys).

...