Learning Outcomes
SLO | After this lecture you will be able to... | CLO | Bloom |
|---|---|---|---|
SLO 9.1 | Explain the parts of a Prolog program and how Prolog answers a query (unification, backtracking) | CLO2 | C2 Understand |
SLO 9.2 | Write facts and rules for a small knowledge base and query it with variables | CLO2 | C3 Apply |
SLO 9.3 | Write a recursive rule and predict the answers and the order Prolog finds them | CLO2 | C3 Apply |
Install: SWI-Prolog is free (swi-prolog.org). All outputs in these notes come from SWI-Prolog 9. Save a program as file.pl, open it with swipl file.pl (or File > Consult), then type queries after ?- and end each with a full stop. Press ; to see the next answer. |
1. What Is Prolog?
§1.1 Declarative programming
Slide L09-S06
Prolog (PROgramming in LOGic) was created by Alain Colmerauer and Robert Kowalski around 1972. In a procedural language (C++, Python) you write the STEPS. In Prolog you write what is TRUE - facts and rules - and ask a question; Prolog searches for the answer itself using unification and resolution (Lecture 8). A Prolog program is a set of Horn clauses: first-order logic rules with one conclusion. Prolog is used in expert systems, language parsing (IBM Watson used it in 2011), scheduling and rule checking.
§1.2 Syntax
Slide L09-S07
Logic (L07) | Prolog | Meaning |
|---|---|---|
Student(Ali) | student(ali). | fact |
∀x Student(x) ∧ Att75(x) → Eligible(x) | eligible(X) :- student(X), att75(X). | rule: head :- body ('if') |
Is Ali eligible? | ?- eligible(ali). | query |
Who is eligible? | ?- eligible(X). | query with a variable |
∧, ∨, ¬ | , ; \+ | and, or, not (negation as failure) |
- Constants and predicate names start with a lower-case letter: ali, student, burewala.
- Variables start with a capital letter or _: X, Student, _ .
- Every clause ends with a full stop.
- Variables in a rule are automatically 'for all' (∀).
2. Facts, Rules and Queries
§2.1 A knowledge base
Slide L09-S09
% L09 - the L07 world as a Prolog knowledge base (facts and rules) student(ali). student(sana). student(bilal). student(hira). teacher(waqas). teacher(ayesha). attendance(ali, 82). attendance(sana, 91). attendance(bilal, 68). attendance(hira, 77). advises(waqas, ali). advises(waqas, sana). advises(ayesha, bilal). advises(ayesha, hira). % Rule: a student is eligible for the final if attendance is 75% or more eligible(X) :- student(X), attendance(X, A), A >= 75. % Rule: T is the advisor of student S (just a renamed relation) advisor_of(S, T) :- advises(T, S). % Rule: two different students share an advisor classmates(X, Y) :- advises(T, X), advises(T, Y), X \= Y. % Negation as failure: short of attendance = a student who is NOT eligible short_attendance(X) :- student(X), \+ eligible(X). |
Real answers from SWI-Prolog:
?- student(ali). true. ?- student(waqas). false. ?- eligible(X). X=ali X=sana X=hira ?- advisor_of(hira, T). T=ayesha ?- classmates(ali, Y). Y=sana ?- short_attendance(X). X=bilal ?- attendance(X, A), A > 80. [X=ali,A=82] [X=sana,A=91] |
student(waqas) is false because it cannot be proved from the KB, not because it is known to be false - this is the closed-world assumption. classmates uses X \= Y ('X and Y cannot be unified') so that Ali is not his own classmate.
§2.2 How Prolog answers: depth-first search and backtracking
Slide L09-S10
Prolog tries goals from LEFT to RIGHT and clauses from TOP to BOTTOM, going as deep as possible first. Each match is a unification. When a goal fails, Prolog BACKTRACKS to the most recent choice and tries the next clause. The program below is a small 'meta-interpreter' (a Prolog program that runs Prolog programs) which prints every step:
% A tiny meta-interpreter that PRINTS how Prolog searches: goals left to right, clauses top to bottom, % and BACKTRACKING to the next clause when a goal fails. :- initialization(main, main). :- consult(university). show(D, Fmt, G) :- tab(D), \+ \+ (numbervars(G, 0, _), format(Fmt, [G])). % prints variables as X, Y, ... solve(true, _) :- !. solve((A, B), D) :- !, solve(A, D), solve(B, D). solve(G, D) :- predicate_property(G, built_in), !, ( call(G) -> show(D, "test ~p yes~n", G) ; show(D, "test ~p NO -> backtrack~n", G), fail ). solve(G, D) :- D2 is D + 2, ( clause(G, Body), ( Body == true -> show(D, "~p matches a fact~n", G) ; show(D, "~p use rule~n", G) ), solve(Body, D2) ; show(D, "~p no other clause -> backtrack~n", G), fail ). main :- Q = (eligible(X), advises(ayesha, X)), show(0, "?- ~p.~n", Q), ( solve(Q, 2) -> format("Answer: X = ~w~n", [X]) ; writeln("false.") ). |
?- eligible(A),advises(ayesha,A). eligible(A) use rule student(ali) matches a fact attendance(ali,82) matches a fact test 82>=75 yes advises(ayesha,ali) no other clause -> backtrack attendance(ali,A) no other clause -> backtrack student(sana) matches a fact attendance(sana,91) matches a fact test 91>=75 yes advises(ayesha,sana) no other clause -> backtrack attendance(sana,A) no other clause -> backtrack student(bilal) matches a fact attendance(bilal,68) matches a fact test 68>=75 NO -> backtrack attendance(bilal,A) no other clause -> backtrack student(hira) matches a fact attendance(hira,77) matches a fact test 77>=75 yes advises(ayesha,hira) matches a fact Answer: X = hira |
Prolog first finds Ali (eligible), but Ayesha does not advise Ali, so it backtracks to student/1 and tries Sana, then Bilal (fails the 75% test), and finally Hira, who succeeds. This is depth-first search - Lecture 10 studies it.
§2.3 Arithmetic, comparison and negation
Slide L09-S11
Prolog | Meaning | Example |
|---|---|---|
X is E | calculate E | X is 2 + 3 gives X = 5 |
X = Y | unify, no calculation | X = 2 + 3 gives X = 2+3 |
> < >= =< | compare numbers (note =<) | 82 >= 75 is true |
=:= =\= | numbers equal / not equal | 4 =:= 2 * 2 is true |
\+ G | G cannot be proved | short_attendance(X) gives bilal |
3. Recursion
§3.1 Reaching cities by road
Slide L09-S13
% L09 - recursion: which cities can be reached by road? (approximate road links, one direction) road(burewala, vehari). road(burewala, arifwala). road(vehari, mailsi). road(vehari, multan). road(arifwala, sahiwal). road(sahiwal, lahore). road(multan, lahore). reachable(X, Y) :- road(X, Y). % base case: a direct road reachable(X, Y) :- road(X, Z), reachable(Z, Y). % recursive case: one road, then keep going route(X, Y, [X, Y]) :- road(X, Y). route(X, Y, [X | Rest]) :- road(X, Z), route(Z, Y, Rest). |
?- reachable(burewala, lahore). true. ?- reachable(lahore, burewala). false. ?- route(burewala, lahore, R). R = [burewala,vehari,multan,lahore] R = [burewala,arifwala,sahiwal,lahore] ?- setof(C, reachable(burewala, C), L). L = [arifwala,lahore,mailsi,multan,sahiwal,vehari] |
A recursive rule has a BASE CASE (a direct road) and a RECURSIVE CASE (one road, then the same problem from the next city). [X | Rest] is a list whose first element is X and whose remaining elements are Rest. Road links are approximate and one-way for teaching.
§3.2 Goal order matters
Slide L09-S14
reach_bad(X, Y) :- reach_bad(Z, Y), road(X, Z). reach_bad(X, Y) :- road(X, Y). |
?- reach_bad(burewala, lahore). ERROR: stack limit exceeded (stack) - infinite recursion |
Logically the same, but Prolog calls reach_bad again before doing any work, forever. Put the base case first and make progress (take a road) before the recursive call. Maps with cycles need an explored set (Lecture 10).
4. Common Mistakes
Wrong idea | Correct idea |
|---|---|
student(Ali). is a fact about Ali. | Ali is a variable; write student(ali). |
X = 2 + 3 gives 5. | Use X is 2 + 3. |
Missing full stop. | Every clause ends with '.' |
false = proved false. | false = cannot be proved (closed world). |
Recursive call first is fine. | It can loop forever. |
Word Bank
Word | Simple meaning | Example |
|---|---|---|
Declarative | Describing what is true, not the steps | Prolog |
Fact | A clause with no conditions | student(ali). |
Rule | head :- body | eligible(X) :- ... |
Query | A question to Prolog | ?- eligible(X). |
Backtracking | Going back to try another choice after a failure | Sana after Ali |
Recursion | A rule that uses itself | reachable/2 |
Closed-world assumption | What cannot be proved is false | student(waqas) is false |
Horn clause | A rule with one conclusion | Every Prolog rule |
Self-Check Questions
- Differentiate declarative and procedural programming. (see §1.1)
- Write 'every Kharif crop needs water' as a Prolog rule. (see §1.2)
- Why is student(waqas) false? (see §2.1)
- Explain the order in which Prolog tries goals and clauses. (see §2.2)
- What is the difference between = and is? (see §2.3)
- Write reachable/2 and name its base and recursive cases. (see §3.1)
- Why does reach_bad loop forever? (see §3.2)
Reading: Luger (6e) 14.1-14.3; SWI-Prolog manual, 'Getting started'.