Prolog Tutorial 0: Getting Started

James Power, 1997.

In this tutorial we just want to have a first shot at running Prolog...

Typing in a Prolog program

Firstly, we want to type in a Prolog program and save it in a file, so, using a Text Editor, type in the following program:


Try to get this exactly as it is - don't add in any extra spaces or punctuation, and don't forget the full-stops: these are very important to Prolog. Also, don't use any capital letters - not even for people's names. Make sure there's at least one fully blank line at the end of the program.

Once you have typed this in, save it as

(Prolog files usually end with ".pl", just as C files end with ".c")

Starting Prolog

Start Prolog at the command prompt; to start GNU Prolog you just type in gprolog. After a while, you should get something like the following on screen:
GNU Prolog 1.2.18
By Daniel Diaz
Copyright (C) 1999-2004 Daniel Diaz
| ?-
The Prolog interpreter is now running and waiting for you to type in some commands.

Loading the Program

Writing programs in Prolog is a cycle involving
  1. Write/Edit the program in a text-editor
  2. Save the program in the text editor
  3. Tell Prolog to read in the program
  4. If Prolog gives you errors, go back to step 1 and fix them
  5. Test it - if it doesn't do what you expected, go back to step 1

We've done the first two of these, so now we need to load the program into Prolog.

The program has been saved as "", so in your Prolog window, type the following and hit the return key:

Don't forget the full-stop at the end of this!

This tells Prolog to read in the file called - you should do this every time you change your program in the text editor. (If your program was called something else, like "", you'd type "other" instead of "intro" above).

You should now have something like the following on screen

| ?- [intro].
compiling /home/jpower/ for byte code...
/home/jpower/ compiled, 5 lines read - 554 bytes written, 7 ms

| ?- 
The "yes" at the end indicates that Prolog has checked your code and found no errors. If you get anything else (particularly a "no"), you should check that you have typed in the code correctly.

At any stage, you can check what Prolog has recorded by asking it for a listing:

| ?- listing.

likes(mary, food).
likes(mary, wine).
likes(john, wine).
likes(john, mary).

| ?-

Running a query

We can now ask Prolog about some of the information it has just read in; try typing each of the following, hitting the return key after each one (and don't forget the full-stop at the end: Prolog won't do anything until it sees a full-stop)

When you're finished you should leave Prolog by typing halt.

Written by James Power
Released under the GNU Free Documentation License
Last revised: 22 Oct 2006