Prolog quickie tutorial


First, we need to define some facts and rules in a file.  Create a file
called "foo" with the following information:

   % Rice krispies rule!      
   krispie( snap ).
   krispie( crackle ).
   krispie( pop ).
   breakfast(A,B,C) :- krispie(A), krispie(B), krispie(C),
                       not(A=B), not(A=C), not(B=C).

Now fire up prolog and load those facts:

   acmez:/tnt2/19/gt5163b> prolog
   SB-Prolog Version 3.1
   | ?- consult(foo).
   yes

Now we can start making queries based on the facts and rules we have
given.  For example, we can verify that snap is a krispie:

   | ?- krispie( snap ).
   yes

and that brian is not:

   | ?- krispie( brian ).
   no

We can also find out a list of all the krispies by using a variable.
Variables start with an uppercase letter.

   | ?- krispie( X ).
   
   X = snap;
   
   X = crackle;
   
   X = pop;
   no

Prolog returns these solutions one at a time, in the order it finds
them.  You can press semicolon (;) to repeat the query and find the next
solution.  Prolog responds "no" when no more valid bindings of the
variables can be found.

Rules are met if all of the predicates on the right-hand side can be
satisfied with some set of bindings.  We can have breakfast with all
three krispies:

   | ?- breakfast(X,Y,Z).
   
   X = snap
   Y = crackle
   Z = pop

Note that if we press semicolon to repeat the query there are more
solutions:

   X = snap
   Y = pop
   Z = crackle

   X = crackle
   Y = snap
   Z = pop
   
   etc...

Note that in the original rule

   breakfast(A,B,C) :- krispie(A), krispie(B), krispie(C),
                       not(A=B), not(A=C), not(B=C).

I had a few nots.  Without them, prolog would be happy to bind muliple
variables to the same value:

   If the rule were...
      breakfast(A,B,C) :- krispie(A), krispie(B), krispie(C).
   Then we'd see...
      | ?- breakfast(A,B,C).
      
      A = snap
      B = snap
      C = snap
      
   etc...


Some handy other things to know: You can consult a file using a
special shorthand notation:
   [bar].
is eqivalent to
   consult(bar).
If you've got a filename with funny characters in it, you'll need to
use single quotes:
   consult('foo.baz').
or
   ['foo.baz'].

Also, if you want to enter rules interactively, you can with user:

   | ?- [user].
   foo(x).
   foo(y).
   <ctrl-d>
   yes
   | ?- foo(A).
   
   A = x;
   
   A = y;
   no


When you're done with prolog, press Ctrl-D:

   | ?- <ctrl-d>
   Halt. Program terminated normally

The best way to get to know prolog is to try it out.  Put together some
facts and rules in a file, and then start prolog and run some queries.
Use examples from class if you're not clever enough to think of your
own silly breakfast cereal examples.  :)

And when you've got questions, ask on the newsgroup, or during office
hours!

Last updated on Mon Oct 12 16:00:22 EDT 1998 by Brian McNamara