Prolog Lab I
Prolog Lab I
Notice that:
• In SWI Prolog, queries are terminated by a full stop.
• To answer this query, Prolog consults its database to see if this is a
known fact.
• In example dialogues with Prolog, the text in green italics is what the
user types.
Another example query
?- lectures(codd, 9020).
false.
• if answer is true., the query succeeded
• if answer is false., the query failed.
Note: Many early versions of Prolog, including early versions of SWI-
Prolog, say No instead of false. In the latest version of SWI Prolog, it
no longer says "No." but says "false." instead.
• The use of lower case for cod is critical.
• Prolog is not being intelligent about this - it would not see a
difference between this query and
lectures(fred, 9020). or lectures(xyzzy, 9020).
though a person inspecting the database can see that fred is a
student, not a lecturer, and that xyzzy is neither student nor
lecturer.
Variables
• Suppose we want to ask, "What course does Turing teach"?
• This could be written as: Is there a course, X, that Turing teaches?
• The variable X stands for an object that the questioner does not
know about yet.
• To answer the question, Prolog has to find out the value of X, if it
exists.
• As long as we do not know the value of a variable it is said to be
unbound.
• When a value is found, the variable is said to bound to that value.
• The name of a variable must begin with a capital letter or an
underscore character, "_".
Variables 2
• To ask Prolog to find the course that Turing teaches, enter this:
?- lectures(turing, Course).
Course = 9020 ← output from Prolog
• To ask which course(s) Prof. Cod teaches, we may ask,
?- lectures(codd , Course).
Course = 9311 ; ← type ";" to get next solution
Course = 9314
?-
• If Prolog can tell that there are no more solutions, it just gives you
the ?- prompt for a new query, as here. If Prolog can't tell, it will let
you type ; again, and then if there is no further solution, report false.
• Prolog can find all possible ways to answer a query, unless you
explicitly tell it not to.
Practice
• On text editor, write the following fact.
female(hanan).
female(aster).
female(ruth).
male(tom).
male(abdu).
male(zola).
mother(hanan,abdu).
mother(hanan,zola).
mother(hanan,aster).
mother(tsehay,ruth).
father(john,ruth).
father(tom,abdu).
father(tom,zola).
father(tom,aster).
parent(zola,tom,hanan).
Save it as anything.pl
Continued…
• Open SWI-Prolog -> File -> Edit [choose the .pl file] ->
Compile[Editor] -> Make [make done] -> On SWI-Prolog, File ->
Edit -> Consult.
• Query
1 ?- parents (zola,F,M).
F=tom,
M=hanan.
2 ?- father (tom,zola).
true
3 ?- father (abc,zola).
F=tom.
Rules
• Extend the fact about some object and their
relationship.
Example:
likes(john,suzie). :- If
likes(suzie,john).
likes(bob,ket). , And
dating(X,Y):-
likes(X,Y),
; Or
likes(X,Y).
Not not
friendship(X,Y).
likes(X,Y);
likes(Y,X).