?- prolog.  TK2313⏱ 00:00plan 0:00☰ slides⛶?
TK2313 Artificial Intelligence · Logic Programming
PROLOG
Introduction & Syntax Familiarization
?- learn(prolog).
true.
Press → or Space to begin · N speaker notes · O overview
Today · 60 minutes

The roadmap

01 · 10 min

Why Prolog?

Declarative thinking · SWI-Prolog
02 · 10 min

Syntax

Atoms · Variables · Terms
03 · 15 min

Facts, Queries, Rules

AND · OR · NOT
04 · 15 min

Under the hood

Unification · Backtracking · Recursion · Lists
05 · 10 min

Debug & Practise

Errors · trace · Challenge
🎯 Goal: read, write and run simple Prolog programs, ready for the Lab.
Part 01

Why Prolog?

Describe what is true, not how to compute it.
01
Two ways to think

Imperative vs Declarative

Python · HOW
parents = [("ali","aminah"), ("aminah","danial")]
for (p, c) in parents:
    for (p2, c2) in parents:
        if c == p2:
            print(p, "is grandparent of", c2)
You write the loops and the order.
Prolog · WHAT
parent(ali, aminah).
parent(aminah, danial).

grandparent(G, C) :- parent(G, P), parent(P, C).
grandparent(G, C).G = ali,\nC = danial.
You state facts & logic. Prolog searches for answers.
The whole idea in one picture

Knowledge + Question → Proof

KNOWLEDGE BASE your program (.pl file) parent(ali, aminah). male(ali). father(F,C) :- ... QUERY ?- father(X, aminah). INFERENCE ENGINE unify · search · backtrack ANSWERS X = ali. or true. / false.
Since 1972 · Colmerauer & Kowalski

Where does Prolog live?

🩺

Expert systems

rules → diagnosis
(our Paddy lab!)
🗣️

Language

parsing & grammars
(NLP in IBM Watson)
🧩

Puzzles & planning

scheduling, Sudoku, constraints
🧠

Knowledge rep.

ontologies, logic & reasoning
Prolog is the hands-on companion to our Knowledge Representation & Logic lectures: facts, rules, inference.
Live demo · open SWI-Prolog

Meet the ?- prompt

1
Open SWI-Prolog (swipl-win, or swipl in a terminal)
2
The prompt ?- means
“ask me something”
3
Every query ends with a full stop . then Enter
4
Quit with halt.
X = hello.X = hello.
write('Hello, Prolog!'), nl.@Hello, Prolog!\ntrue.
X is 6 * 7.X = 42.
Rule #1 of working in Prolog

Facts go in a file.
Questions go at ?-

📄 program · .pl file
Facts & rules: the knowledge.
Loaded with consult.
?- query · console
Questions about the knowledge.
Prolog answers true / false / values.
parent(ali, aminah).!ERROR: Unknown procedure: parent/2 (DWIM could not correct goal)
☝ Typing a fact at ?- does not add it. Prolog treats it as a question about a program that isn't loaded yet.
Two ways to load code

Getting code into Prolog

A · file (recommended)
1
Save the demo file as tk2313_prolog_intro.pl
2
Load it (or File ▸ Consult…):
consult('C:/Users/me/Desktop/tk2313_prolog_intro.pl').true.
Use forward slashes / in Windows paths. After editing the file, reload with make.
B · quick paste
[user].@|: ← paste clauses here
Paste facts & rules, then end input with
Ctrl + D (Windows console: Ctrl+Z, Enter)
Great for tiny demos, but the code is lost when you quit. Use a file for real work.
Part 02

The building blocks

Everything in Prolog is a term.
02
One data type to rule them all

Everything is a term

term constant variable X Food _ compound parent(ali, aminah) [1, 2, 3] atom ali 'Kuala Lumpur' number 42 3.14 -7
Constants · names of things

Atoms start lowercase

a
lowercase letter first: ali nasi_lemak tk2313
'
anything in single quotes: 'Kuala Lumpur' 'Ali'
+
symbol sequences: + =.. []
❌ Ali is not an atom, it is a variable!
❌ nasi lemak has a space. Use nasi_lemak.
atom(ali).true.
atom('Kuala Lumpur').true.
atom(Ali).false.
Unknowns to be found

Variables start Uppercase or _

X
X Who Food _Temp
_
Anonymous _ means “I don't care what it is”
=
A variable gets a value once: no X = X + 1 like in Python
↻
Same name in one clause = same value
X = 5, Y = X.X = Y, Y = 5.
X = 5, X = 6.false.
parent(ali, _).true ;\ntrue.
Structures

Compound terms: functor + arguments

parent(ali, aminah). functor (name) arguments parent/2name / arity (no. of args) full stop
parent/2 and parent/3 are different predicates. No space before (!
Quick check · shout it out!

Atom, variable, number or invalid?

siti
atom
Siti
variable
_x
variable
'Siti'
atom
3.14
number
roti canai
invalid: space
age(ali,72)
compound /2
2nd_place
invalid: digit first
Part 03

Facts, Queries & Rules

Our running example: one Malaysian family 👨‍👩‍👧‍👦
03
Facts · things that are simply true

Facts: relation(object, …).

parent(ali, aminah).
parent(ali, badrul).
parent(siti, aminah).
parent(siti, badrul).
parent(aminah, danial).
parent(badrul, farah).
parent(danial, hana).

male(ali).     female(siti).
male(badrul).  female(aminah).
male(danial).  female(farah).
               female(hana).
ali 72 siti 68 aminah 45 badrul 41 danial 24 farah 16 hana 2
Queries · ask a question

Yes/no questions → true / false

parent(ali, aminah).true ;\nfalse.
parent(aminah, ali).false.
male(hana).false.
Closed world: if Prolog can't prove it from the program, the answer is false. It does not mean “impossible”, only “not known”.
Why true ; then false?
Prolog found it but still had another parent(ali, …) fact to try. Press ; to check it: no more, so false. Press Enter to stop instead.
Queries · let Prolog find values

Variables ask “who?” / “what?”

parent(ali, X).X = aminah ;\nX = badrul.
parent(X, danial).X = aminah.
likes(Who, nasi_lemak).Who = aminah ;\nWho = danial.
after each answer
;
next answer
(backtrack)
Enter
stop, I'm happy
Translate: “Is there an X such that ali is a parent of X?”
Comma , = AND

Combine goals with ,

parent(ali, X), female(X).X = aminah ;\nfalse.
parent(siti, P), parent(P, G).P = aminah,\nG = danial ;\nP = badrul,\nG = farah.
The same variable links the goals: the X found in goal 1 must also pass goal 2.
Query 2 = “grandchildren of siti”. We'll turn it into a reusable rule next.
Rules · knowledge that depends on other knowledge

Anatomy of a rule

father(F, C) :- parent(F, C), male(F).
HEAD
the conclusion
:- IF
“is true if”
BODY
conditions, joined by , = AND
🗣 “F is the father of C if F is a parent of C and F is male.”
Live demo · rules in the demo file

Family rules

father(F, C)      :- parent(F, C), male(F).
mother(M, C)      :- parent(M, C), female(M).
grandparent(G, C) :- parent(G, P), parent(P, C).
sibling(X, Y)     :- parent(P, X), parent(P, Y), X \= Y.
🤔 Why does badrul appear twice?
Aminah and Badrul share two parents, so it is proved once via ali and once via siti.
father(F, aminah).F = ali ;\nfalse.
grandparent(ali, Who).Who = danial ;\nWho = farah.
sibling(aminah, S).S = badrul ;\nS = badrul.
Two ways to say OR

OR = ; or several clauses

guardian(G, C) :- parent(G, C).
guardian(G, C) :- grandparent(G, C).
guardian(ali, C).C = aminah ;\nC = badrul ;\nC = danial ;\nC = farah.
Same meaning, one clause:
guardian(G,C) :- parent(G,C) ; grandparent(G,C).
parent(ali, X) ; parent(danial, X).X = aminah ;\nX = badrul ;\nX = hana.
Prefer separate clauses: easier to read and debug.
NOT

\+ = “cannot be proved”

\+ male(siti).true.
\+ parent(hana, _).true.
Negation as failure: \+ G succeeds if G fails.
Also written not(G).
Query 2: “Hana has no children” is true because no fact says she has.
Part 04

Under the hood

Unification · Arithmetic · Backtracking · Recursion · Lists
04
The heart of Prolog

Unification = makes two terms identical

term A
f / 2
X
b
term B
f / 2
a
Y
result
① functor ✓
② X = a
③ Y = b
f(X, b) = f(a, Y).X = a,\nY = b.
point(X, X) = point(1, 2).false.
likes(aminah, F) = likes(Who, nasi_lemak).F = nasi_lemak,\nWho = aminah.
Most common confusion

Four kinds of “equal”

operatormeaningexampleresult
=unify (pattern match)X = 1 + 2X = 1+2 no maths!
isevaluate right sideX is 1 + 2X = 3
=:=numbers equal?2 + 1 =:= 3true
==identical terms?2 + 1 == 3false
X = 1 + 2.X = 1+2.
X is 1 + 2.X = 3.
Numbers

Arithmetic & comparison

+-*///mod**
<>=<>==:==\=
⚠ It's =<, not <= (that looks like an arrow ⇐ in Prolog).
adult(X)    :- age(X, A), A >= 18.
teen(X)     :- age(X, A), A >= 13, A =< 19.
older(X, Y) :- age(X, A), age(Y, B), A > B.
X is 7 / 2, Y is 7 // 2, Z is 7 mod 2.X = 3.5,\nY = 3,\nZ = 1.
teen(X).X = farah ;\nfalse.
age(X, A), A < 20.X = farah,\nA = 16 ;\nX = hana,\nA = 2.
How Prolog searches

Backtracking: depth-first, left-to-right

?- parent(ali, X), female(X). ① parent(ali, aminah)EXIT · X = aminah ② female(aminah) ✓ X = aminah ; ③ REDO → parent(ali, badrul) ④ female(badrul) ✗ no more → false.
Depth-first: finish one path completely before trying another.
Backtrack: on failure (or ;), undo the last choice and try the next clause.
Rules that use themselves

Recursion: ancestor

ancestor(A, D) :- parent(A, D).                  % base case
ancestor(A, D) :- parent(A, X), ancestor(X, D).  % recursive
ancestor(ali, hana).true ;\nfalse.
ancestor(A, hana).A = danial ;\nA = ali ;\nA = siti ;\nA = aminah ;\nfalse.
ali parent → recurseaminah parent → recursedanial base case ✓hana
Always put the base case first, and make each recursive step move closer to it, or the recursion never stops.
The workhorse data structure

Lists: [Head | Tail]

nasi_lemak
satay, laksa
HEADTAIL (also a list)
[H|T] = [nasi_lemak, satay, laksa].H = nasi_lemak,\nT = [satay, laksa].
member(satay, [nasi_lemak, satay]).true.
my_sum([10, 20, 30], S).S = 60.
my_sum([], 0).
my_sum([H|T], S) :- my_sum(T, S0), S is H + S0.
Cheat sheet

Handy built-ins

findall(C, parent(ali, C), Kids).Kids = [aminah, badrul].
append([1,2], [3], L).L = [1, 2, 3].
length([a,b,c], N).N = 3.
greet(aminah).@Selamat datang, aminah!\ntrue.
format("~w is ~w years old~n", [ali, 72]).@ali is 72 years old\ntrue.
listing(father).@father(F, C) :-\n@ parent(F, C),\n@ male(F).\ntrue.
Part 05

Debug & practise

Read the error message. It tells you the line number.
05
Real SWI-Prolog messages

Top 5 beginner errors

1 · missing full stop
likes(ali, satay) ← no "." ERROR: file.pl:1:18: Syntax error: Operator expected
✓ end every clause with . (it also swallows the next line!)
2 · uppercase predicate
?- Parent(ali, X). ERROR: Syntax error: Operator expected
✓ predicate names are atoms → lowercase
3 · program not loaded / typo / wrong arity
ERROR: Unknown procedure: parent/2
✓ consult the file · check spelling · count the arguments
4 · singleton variable (warning)
bad(X, ali). Warning: Singleton variables: [X]
✓ used only once? Probably a typo, or write _
5 · maths on an unknown
?- X is Y + 1. ERROR: Arguments are not sufficiently instantiated
✓ give Y a value first: Y = 4, X is Y + 1.
And: typing a fact at ?- asks a question. It doesn't store anything.
See Prolog think

trace. step through a proof

trace, father(F, aminah).@ Call: (11) father(_16410, aminah) ? creep\n@ Call: (12) parent(_16410, aminah) ? creep\n@ Exit: (12) parent(ali, aminah) ? creep\n@ Call: (12) male(ali) ? creep\n@ Exit: (12) male(ali) ? creep\n@ Exit: (11) father(ali, aminah) ? creep\nF = ali .
C
Call: try to prove
E
Exit: proved
R
Redo: backtrack in
F
Fail: no proof
Press Enter to creep step by step · notrace. to switch off · nodebug. to leave debug mode
⏱ 5-minute challenge · in pairs

Your turn

1
Write grandmother(G, C)
2
Write uncle(U, C): brother of a parent
3
Query: who likes the same food as aminah?
4
Bonus: count_kids(P, N) using findall + length
same_taste(aminah, Who).Who = danial.
count_kids(ali, N).N = 2.
grandmother(G, C) :- grandparent(G, C), female(G).

uncle(U, C) :- parent(P, C), sibling(U, P), male(U).

count_kids(P, N) :- findall(C, parent(P, C), Kids),
                    length(Kids, N).
uncle(U, danial).U = badrul ;\nU = badrul ;\nfalse.
Take-home cheat sheet

Prolog on one slide

fact.always true: parent(ali, aminah).%comment to end of line
h :- b.rule: h is true if b is true/* */block comment
,   ;   \+AND · OR · NOT[H|T]list head & tail
X   _variable · don't-careisevaluate maths
=unify (match)=< >=compare numbers
; / Enternext answer / stopmake.reload edited file
Up next
PROLOG//LAB
Guided exercises · unification · resolution · cut · lists · expert system
?- questions(class).▌

All slides · click to jump · O to close