Introduction to Prolog programming

Introduction:

"Prolog is a computer programming language that is used for solving problems that involve objects and the relationships between objects."Fundamentals of Prolog:

1. Facts example: "John likes Mary", we can write this fact in prolog like: likes(john, mary).

More examples:

In Prolog, a collection of facts is called a database.

2. Questions

Once we have some facts, we can ask questions about them.

example: ?-owns(mary, book). This question is asking "Does Mary own the book?"

3. Variables

example: ?-likes(john, X). This question is asking "Is there anything that John likes?"

If yes, what's that?" Here, X is a variable. Prolog will respond with an answer. "No" stands for John likes nothing. If John likes more than one things, Prolog will give you one answer. You can type ";" after that answer, Prolog will continue to find new answers until it reach the end of database.

4. Conjunctions

example: ?-likes(john, mary), likes(mary, john). This question is asking "Does John like Mary? and does Mary like John?" comma here stands for "and".

Try asking questions "?-likes(mary,X), likes(john, X)" when running example1.

5. Rules

"In Prolog, rules are used when you want to say that a fact depends on a group of other facts. In English, we use the word if to express a rule".

example: X is a bird if: X is an animal, and X has feathers.

We can express this in Prolog as: bird(X):-animal(X), has(X, feathers).

":-" is pronounced as "if".

Assignment:

1. Read http://www.macalester.edu/%7Eshoop/courses/CS42_S02/prolog_howto.html carefully.

Instead of using 'holmes.prolog' example mentioned in the webpage, use example1 as sample program.

You can download metro1.plg example mentioned in the website here.

After running example1, try to run metro1 example.detailed steps for running example1:

(a) login linux
(b) save file example1 into your project directory.
(c) enter your project directory.
(d) open a command window and type "pl". You should see message as: "Welcome to SWI-Prolog..."
(e) type "[example1]." Prolog will read in example1 file and compile it. You should see message: "% example1 compiled 0.00 sec, 1,000 bytes".
(f) type command "listing." You should be able to see the relations defined in the source file.
(g) type command "has(jack,apples)." "has(jack,wine)." "has(jack, X)." "has(X,apples),has(Y,plums). "
"has(X,apples),has(X,plums). " "has(dan,X),fruit(X). " "has(X,Y),not fruit(Y). " read the source code and try to understand the answers.

2. Write your own prolog program. (need to check out by TA, don't forget. )

Write a program to test if X is a sister of Y : sisterof(X,Y).
Rules: X is a sister of Y if :

Database:

male(tom).
male(john).
female(alice).
female(mary).
parents(tom, alice, john). (note: meaning: the parents of tom are alice and john)
parents(mary, alice, john).

Question:

sisterof(tom, alice).
sisterof(tom, X).

sisterof(X,Y).