CS 224 Lab 5 - Prolog Searches
Follow the algorithms of unification and search in Prolog
- Login to your account on phoenix. Copy the file lab7.pl from ~jillz/cs224.
- We have already talked about unification which is the process by which variables are instantiated. This means that the variables are allocated memory and assigned values so that patterns match during resolution. Let's experiment with unification using the equality operator which attempts to unify two terms. Try the following in prolog:
me = me.
me = you.
me = X.
f(a,X) = f(Y,b).
f(X) = g(X).
f(X) = f(a,b).
f(a,g(X)) = f(Y,b).
f(a,g(X)) = f(Y,g(b)).
From the experiments above you should see that a
constant unifies only with itself, and a variable that is uninstantiated
unifies with any constant and becomes instantiated to that value.
Describe from your experiments above the rules for unification that involves a structured term (i.e. a pattern with arguments)
- What happens if we try to unify two uninstantiated variables? Try
X = Y.
What happens is that prolog returns something like:
The _23 is just some internal memory location. The number that you got is probably different. These two variables are both sharing the same memory location - i.e. they are aliases.
- We have seen how depth first search with backtracking can be used to perform loops in prolog. There is a predicate
fail available in prolog to force backtracking. Take a look at the file lab7.pl. This file defines the relation printpieces. The
fail at the end forces backtracking to occur. What do you think the relation does? Try it with the query:
Take a look at the relation num.
Draw at least three levels of the search tree that would result in the
query num(X). (This is of course an infinite search tree so you
canít draw it all.)
- Try using the relation writenum which uses fail to loop, to write the integers from 1 to 3.
Warning: There is a problem here so beware! What happened and why?
- To fix this problem we need to use something that is called the cut operator in prolog. The cut operator is denoted by "!" and if a cut is reached on backtracking, the search of siblings are cut (or not searched) in the search tree.
Change writenum as follows to include a cut and try it again.
writenum(I,J) :- num(X), I =< X, X =< J, write(X), nl, X = J, !, fail.
- A cut can be used to imitate an if-then-else structure. To write a clause such as
D = if A then B else C
we write the following prolog:
D :- A, !, B.
D :- C.
Explain why the
prolog code above will have the desired result
of a conditional.
Section 20.6 in the text describes
"The Lighter Side of Prolog" with an example of a little text-based
adventure game. Read this section which describes the predicates assert and retract. Copy the file game.pl from ~jillz/cs224 and complete exercise 6 on p444. Enjoy!