CS 152 - Lecture 18

Cover page image

Cay S. Horstmann

Prolog 1

What is Prolog?

The Canonical Example - Facts

The Canonical Example - Queries

The Canonical Example - Rules

Function Symbols

Prolog Jargon

Lab

???

Step 0

This lab requires SWI Prolog. In Linux, sudo apt-get install swi-prolog. Read their documentation for Mac OS X and Windows instructions, or just install in a Linux virtual machine.

Note: Didn't install the software before the lab? Try to use https://swish.swi-prolog.org/

Download the family.prolog file and put it into your home directory.

Start SWI Prolog:

  1. Open a shell window
  2. Change to the lab subdirectory
  3. On Linux, run swipl. On Mac OS X and Windows, check their docs.

In the Prolog shell, type

consult('family.prolog').

This loads the family.prolog facts into Prolog. Note the period at the end of the command.

If you get a message that the file was not found, perhaps you are not in the right directory. Run the cd command, like this:

cd('/home/me/cs152/lab17/').

Note that there is no space after cd, the quotes are single quotes, and there is a period at the end of the command.

Step 1

  1. Issue queries to find the children of charles1 and the parents of george1. Which queries did you issue, and what was the result?
  2. Define a grandparent predicate. Add it to family.prolog. Reload the file again with consult. What is the rule defining your predicate? Which query yields the grandparents of sophia? The grandchildren of james1? What are the results?
  3. Define a sibling predicate in the same way. What query did you use to test it?

Step 2

  1. Add the following rules to family.prolog
    ancestor(X, Y) :- parent(X, Y).
    ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

    Which query yields the ancestors of sophia? The descendants of james1? What are the results?

  2. Type the command
    trace.

    (Remember the period at the end.)

    Now issue the query

    ancestor(X, sophia).

    Each time execution halts with a ? prompt, hit Enter. Each time you get another answer, type a semicolon (;) as you did previously.

    What happens?

    Turn debugging off by typing

    nodebug.
  3. Change the second rule for ancestor to
    ancestor(X, Y) :- ancestor(Z, Y), parent(X, Z).

    Intuitively, this should not change the behavior of ancestor. Reload family and try out

    ancestor(X, sophia).

    Be sure to enumerate all answers.

    What happens?

    (Hit a to abort.)

  4. Turn tracing on, study the behavior and explain the reason for the behavior. (I found this less tedious after commenting out all but two of the parent facts in family.pl. In prolog, a line starting with % is a comment.
  5. Also try out the GUI tracer. Call
    guitracer.
    and then run a trace. To switch back to the command line tracer, use noguitracer.