You are on page 1of 117

Introduction to Prolog

Amey Karkare
karkare @ cse.iitk.ac.in

Dept of CSE, IIT Kanpur

Oct-21 p.1/41
Goals

• Logic and Horn Clauses


• Introduce basic concepts in Prolog
• Start with Prolog interpreter
• Share some tips and tricks of Prolog

Textbook:
Chapter 15, Programming Languages, Tucker and Noonan
Some interpreters:
https://www.swi-prolog.org/
http://xsb.sourceforge.net/

Oct-21 p.2/41
Logic and Horn Clauses

• A Horn clause has a head ℎ, which is a predicate, and a body,


which is a list of predicates 𝑝1, 𝑝2, … , 𝑝𝑛.
• It is written as:
ℎ ← 𝑝! , 𝑝" , … , 𝑝#
• This means, “h is true if p1, p2, …, and pn are simultaneously true.”
𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ⇒ ℎ

Oct-21 p.2/41
Logic and Horn Clauses

• A Horn clause has a head ℎ, which is a predicate, and a body,


which is a list of predicates 𝑝1, 𝑝2, … , 𝑝𝑛.
• It is written as:
ℎ ← 𝑝! , 𝑝" , … , 𝑝#
• This means, “h is true only if p1, p2, …, and pn are simultaneously
true.”
𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ⇒ ℎ

Example:

𝑏𝑟𝑜𝑡ℎ𝑒𝑟 𝑏! , 𝑏" ← 𝑠𝑜𝑛 𝑏! , 𝑓 , 𝑠𝑜𝑛 𝑏" , 𝑓 , 𝑛𝑜𝑡_𝑠𝑎𝑚𝑒(𝑏! , 𝑏" )

It says: 𝑏! is a brother of 𝑏" if 𝑏! is a son of 𝑓 and 𝑏" is a son of 𝑓 and


they are not the same person.

Oct-21 p.2/41
Logic and Horn Clauses

• A Horn clause has a head ℎ, which is a predicate, and a body,


which is a list of predicates 𝑝1, 𝑝2, … , 𝑝𝑛.
• It is written as:
ℎ ← 𝑝! , 𝑝" , … , 𝑝#
• This means, “h is true only if p1, p2, …, and pn are simultaneously
true.”
𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ⇒ ℎ

Example:

𝑏𝑟𝑜𝑡ℎ𝑒𝑟 𝑏! , 𝑏" ← 𝑠𝑜𝑛 𝑏! , 𝑓 , 𝑠𝑜𝑛 𝑏" , 𝑓 , 𝑛𝑜𝑡_𝑠𝑎𝑚𝑒(𝑏! , 𝑏" )

It says: 𝑏! is a brother of 𝑏" if 𝑏! is a son of 𝑓 and 𝑏" is a son of 𝑓 and


they are not the same
Noteperson.
that the clause is Correct but incomplete.
Not very important for the current discussion.
Oct-21 p.2/41
Logic and Horn Clauses

• Any Horn clause


ℎ ← 𝑝! , 𝑝" , … , 𝑝#
• Is equivalent to
𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ⇒ ℎ
• Or
¬(𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ) ∨ ℎ

Oct-21 p.2/41
Logic and Horn Clauses

• Any Horn clause


ℎ ← 𝑝! , 𝑝" , … , 𝑝#
• Is equivalent to
𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ⇒ ℎ
• Or
¬(𝑝! ∧ 𝑝" ∧ ⋯ ∧ 𝑝# ) ∨ ℎ

• Not every predicate is equivalent to a Horn Clause

𝑚𝑜𝑟𝑡𝑎𝑙 𝑥 ⇒ ℎ𝑢𝑚𝑎𝑛 𝑥 ∨ 𝑎𝑛𝑖𝑚𝑎𝑙(𝑥)

Oct-21 p.2/41
Resolution and Unification

If ℎ is the head of a Horn clause


ℎ ← 𝑡𝑒𝑟𝑚𝑠
and it matches one of the terms of another Horn clause:
𝑡 ← 𝑡1, ℎ, 𝑡2
then that term can be replaced by ℎ’s terms to form:
𝑡 ← 𝑡1, 𝑡𝑒𝑟𝑚𝑠, 𝑡2

Oct-21 p.2/41
Resolution and Unification

If ℎ is the head of a Horn clause


ℎ ← 𝑡𝑒𝑟𝑚𝑠
and it matches one of the terms of another Horn clause:
𝑡 ← 𝑡1, ℎ, 𝑡2
then that term can be replaced by ℎ’s terms to form:
𝑡 ← 𝑡1, 𝑡𝑒𝑟𝑚𝑠, 𝑡2

During resolution, assignment of variables to values is called instantiation.

Oct-21 p.2/41
Resolution and Unification

If ℎ is the head of a Horn clause


ℎ ← 𝑡𝑒𝑟𝑚𝑠
and it matches one of the terms of another Horn clause:
𝑡 ← 𝑡1, ℎ, 𝑡2
then that term can be replaced by ℎ’s terms to form:
𝑡 ← 𝑡1, 𝑡𝑒𝑟𝑚𝑠, 𝑡2

During resolution, assignment of variables to values is called instantiation.

Unification is a pattern-matching process that determines what particular


instantiations can be made to variables during a series of resolutions.

Oct-21 p.2/41
Resolution: Example

The two clauses:


speaks(Mary, English)
talkswith(X, Y) ← speaks(X, L),
speaks(Y, L),
X¹Y

can resolve to:


talkswith(Mary, Y) ← speaks(Mary, English),
speaks(Y, English),
Mary ¹ Y

The assignment of values Mary and English to the variables X and L is an


instantiation for which this resolution can be made.

Oct-21 p.2/41
Resolution: Example

Resolutions help to arrive at conclusions.

speaks(Mary, English)
speaks(Ram, Hindi)
speaks(Ana, English)

talkswith(X, Y) ← speaks(X, L),


speaks(Y, L),
X¹Y

Can you find out who can Mary talk with?

Oct-21 p.2/41
Logic Programming in Prolog

• In logic programming the program declares the goals of the computation,


not the method for achieving them.

• Logic programming has applications in


• AI and databases.
• Natural language processing (NLP)
• Automated reasoning and theorem proving
• Expert systems (e.g., MYCIN)
• Database searching, as in SQL (Structured Query Language)

• Prolog emerged in the 1970s. Distinguishing features:


• Nondeterminism
• Backtracking

Oct-21 p.2/41
Prolog System

Prolog
Programmer Data
Base

Prolog
User
Query Interpreter Answer

Oct-21 p.3/41
A Real Life Example

Long time ago, CSE Courses at some IIT in some Semester


• Courses Offered
Course# Offered By Course# Offered By
CS 606 ranade CS 613 as
CS 630 sundar CS 638 uday
CS 686 rkj CS 152 as
CS 154 as CS 350 karkare
CS 394 uday CS 640 krishnas

Oct-21 p.4/41
A Real Life Example

Long time ago, CSE Courses at some IIT in some Semester


• Courses Offered
Course# Offered By Course# Offered By
CS 606 ranade CS 613 as
CS 630 sundar CS 638 uday
CS 686 rkj CS 152 as
CS 154 as CS 350 karkare
CS 394 uday CS 640 krishnas
• Students Enrolled
Course Students
CS 638 5007, 5020, 5026, 5601, 5044, 5401, . . .
CS 612 5601, 5401, 5044, 5003, 5023, 5024, . . .
... ...

Oct-21 p.4/41
A Real Life Example (Contd. . . )

• Simple Queries:

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?
• Complex Queries:

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?
• Complex Queries:
◦ List all professors who teach student with roll # 5044.

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?
• Complex Queries:
◦ List all professors who teach student with roll # 5044.
◦ What are all the courses offered by Prof. uday?

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?
• Complex Queries:
◦ List all professors who teach student with roll # 5044.
◦ What are all the courses offered by Prof. uday?
◦ Make pairs of students enrolled in CS 638, such that
both students in a pair are not enrolled in same course
(Of course, other than CS638).

Oct-21 p.5/41
A Real Life Example (Contd. . . )

• Simple Queries:
◦ Who teaches CS 350?
◦ What is the course offered by Prof. rkj?
◦ Who are the students enrolled in CS 638?
• Complex Queries:
◦ List all professors who teach student with roll # 5044.
◦ What are all the courses offered by Prof. uday?
◦ Make pairs of students enrolled in CS 638, such that
both students in a pair are not enrolled in same course
(Of course, other than CS638).

Need to encode the data for Prolog Interpreter.

Oct-21 p.5/41
Time to learn Prolog syntax!

Oct-21 p.6/41
Prolog Syntax: Atoms

• Building blocks of Prolog.

Oct-21 p.7/41
Prolog Syntax: Atoms

• Building blocks of Prolog.


• lowercase letter followed by lower/uppercase letter,
underscore and digits, e.g. course, cs638, len N.

Oct-21 p.7/41
Prolog Syntax: Atoms

• Building blocks of Prolog.


• lowercase letter followed by lower/uppercase letter,
underscore and digits, e.g. course, cs638, len N.
• anything enclosed in single quotes(’), e.g.
’Dept of CSE’, ’&%$ >’, ’Address’.

Oct-21 p.7/41
Prolog Syntax: Atoms

• Building blocks of Prolog.


• lowercase letter followed by lower/uppercase letter,
underscore and digits, e.g. course, cs638, len N.
• anything enclosed in single quotes(’), e.g.
’Dept of CSE’, ’&%$ >’, ’Address’.
• string of special characters (Reserved words), e.g. :-, ;, .,
,.

Oct-21 p.7/41
Prolog Syntax: Numbers

• integers – . . . , -3, -2, -1, 0, 1, 2, 3, . . .

Oct-21 p.8/41
Prolog Syntax: Numbers

• integers – . . . , -3, -2, -1, 0, 1, 2, 3, . . .


• floating point numbers – 3.1416, 2.7138, 0.001

Oct-21 p.8/41
Prolog Syntax: Numbers

• integers – . . . , -3, -2, -1, 0, 1, 2, 3, . . .


• floating point numbers – 3.1416, 2.7138, 0.001
• We will be working mostly with integers.

Oct-21 p.8/41
Prolog Syntax: Variables

• uppercase letter followed by lower/uppercase letter,


underscore and digits, e.g. Course, Cs_350, Len.

Oct-21 p.9/41
Prolog Syntax: Variables

• uppercase letter followed by lower/uppercase letter,


underscore and digits, e.g. Course, Cs_350, Len.
• underscore followed by lower/uppercase letter, underscore
and digits, e.g. course, 638, Len.

Oct-21 p.9/41
Prolog Syntax: Variables

• uppercase letter followed by lower/uppercase letter,


underscore and digits, e.g. Course, Cs_350, Len.
• underscore followed by lower/uppercase letter, underscore
and digits, e.g. course, 638, Len.
• (underscore only) is special anonymous variable.

Oct-21 p.9/41
Prolog Syntax: Variables

• uppercase letter followed by lower/uppercase letter,


underscore and digits, e.g. Course, Cs_350, Len.
• underscore followed by lower/uppercase letter, underscore
and digits, e.g. course, 638, Len.
• (underscore only) is special anonymous variable.

Attention: Two occurrences of are different variables.

Oct-21 p.9/41
Prolog Syntax: Complex Terms

• functor followed by arguments, e.g.


brother(ram, lakshman)
capital(india, delhi)
set level(X, next(Current))

Oct-21 p.10/41
Prolog Syntax: Complex Terms

• functor followed by arguments, e.g.


brother(ram, lakshman)
capital(india, delhi)
set level(X, next(Current))
• functor must be an atom.

Oct-21 p.10/41
Prolog Syntax: Complex Terms

• functor followed by arguments, e.g.


brother(ram, lakshman)
capital(india, delhi)
set level(X, next(Current))
• functor must be an atom.
• arguments can be any kind of prolog terms (atom, number,
variable, complex term).

Oct-21 p.10/41
Prolog Syntax: Facts

• Complex terms followed by full-stop(.).


• Used to state unconditional truth.

Oct-21 p.11/41
Example: Facts

% offered by(+Course, +Prof):


% database of courses offered by professors.
offered by(cs606, ranade).
offered by(cs613, as).
offered by(cs630, sundar).
offered by(cs638, uday).
offered by(cs686, rkj).
offered by(cs152, as).
offered by(cs154, as).
offered by(cs324, uday).
offered by(cs394, uday).
offered by(cs640, krishnas).
offered by(cs350, karkare).

Oct-21 p.12/41
Example: Facts (Contd. . . )

% enrolled(+Course, +RollNo):
% database of students enrolled in courses
enrolled(cs638, 5007).
enrolled(cs638, 5020).
enrolled(cs638, 5026).
enrolled(cs638, 5601).
enrolled(cs638, 5044).
enrolled(cs638, 5401).
.
.
enrolled(cs612, 5601).
enrolled(cs612, 5401).
enrolled(cs612, 5044).
enrolled(cs612, 5003).
enrolled(cs612, 5023).
enrolled(cs612, 5024).
.
.

Oct-21 p.13/41
Prolog Syntax: Queries

• Complex terms followed by full-stop(.).

Oct-21 p.14/41
Prolog Syntax: Queries

• Complex terms followed by full-stop(.).

Wait!!! Isn’t that what a Fact is?

Oct-21 p.14/41
Prolog Syntax: Queries

• Complex terms followed by full-stop(.).

Wait!!! Isn’t that what a Fact is?

• Queries are not unconditional truth, but a question asked.


Prolog interpreter need to infer the truth of queries.

Oct-21 p.14/41
Prolog Quick-start

• Save the facts in a file, say course.pl


• Run Prolog Interpreter
• load the file in the interpreter (could differ for different interpreters).

Oct-21 p.15/41
Example: Queries

| ?- offered by(cs350, X).

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?-

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?-

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007

Oct-21 Proo
lg p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;
X = 5401

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;
X = 5401;

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;
X = 5401;
no
| ?-

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;
X = 5401;
no
| ?- offered by(cs158, X).

Oct-21 p.16/41
Example: Queries

| ?- offered by(cs350, X).


X = karkare
yes
| ?- offered by(X, rkj).
X = cs686
yes
| ?- enrolled(cs638, X).
X = 5007;
X = 5020;
X = 5026;
X = 5601;
X = 5044;
X = 5401;
no
| ?- offered by(cs158, X).
no
| ?-

Oct-21 p.16/41
Points to Note

• Note the . (full-stop) at the end of queries (and facts).


• Answer is typically given as a binding to variable(s).
• yes means prolog was able to find an answer.
• no means prolog could not find an answer.
• Entering ; asks prolog to search for more answers, i.e. a
different binding to variables satisfying the query.

Oct-21 p.17/41
Prolog Syntax: Rules

• Rules are conditional truth!, i.e. if something then


something-else.
• The syntax is: Head :- Body.
• Head is a complex term.
• Body is a sequence of complex terms (possibly only one),
separated by commas(,).

Oct-21 p.18/41
Example: Rules

• Conjunction
teaches(Prof, Student) :-
offered by(Course, Prof),
enrolled(Course, Student).

Oct-21 p.19/41
Example: Rules

• Disjunction
likes compiler(Student) :-
enrolled(cs638, Student).
likes compiler(Student) :-
enrolled(cs613, Student).

Oct-21 p.20/41
Example: Rules

• Disjunction
likes compiler(Student) :-
enrolled(cs638, Student).
likes compiler(Student) :-
enrolled(cs613, Student).
• Attention:
Check that the different bodies of disjunctive clauses are:

Oct-21 p.20/41
Example: Rules

• Disjunction
likes compiler(Student) :-
enrolled(cs638, Student).
likes compiler(Student) :-
enrolled(cs613, Student).
• Attention:
Check that the different bodies of disjunctive clauses are:
◦ Mutually exclusive - unless you are really sure you want
multiple, non-deterministic answers

Oct-21 p.20/41
Example: Rules

• Disjunction
likes compiler(Student) :-
enrolled(cs638, Student).
likes compiler(Student) :-
enrolled(cs613, Student).
• Attention:
Check that the different bodies of disjunctive clauses are:
◦ Mutually exclusive - unless you are really sure you want
multiple, non-deterministic answers
◦ Exhaustive - cover all the cases, possibly implicitly

Oct-21 p.20/41
Example: Rules

• Negation
dislikes compiler(Student) :-
not(likes compiler(Student)).

Oct-21 p.21/41
Example: Rules

• Negation
dislikes compiler(Student) :-
not(likes compiler(Student)).
• Warning:
Negation may not work as expected (Why?)

Oct-21 p.21/41
Matching

• The process of finding solutions to a query.

Oct-21 Proo
lg p.22/41
Matching

• The process of finding solutions to a query.


• = predicate tests if its arguments match (note that we say
match, not equal).

Oct-21 p.22/41
Matching: Atoms, Variables

• Same atoms match. e.g.


cs613 matches cs613, i.e. cs613 = cs613
’cs638’ = cs638 (Surprised?)

54 does not match ’54’ (Surprised Again?)

• A variable matches any other term.

X = cs638
Z = Y
W = left(right(building(bricks,walls)))
_ = 5004

Oct-21 p.23/41
Matching: Complex Terms

• Two complex term match if:


◦ they have same functor, and
◦ they have same arity, and
◦ their corresponding arguments match, without any clash.

left(X) = left(right(building(bricks)))

father(X, dashrath) \= father(ram, X)

father( , dashrath) = father(ram, ) (Why?)

id(1, 1) = id(X, X)

Oct-21 p.24/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod

Oct-21 p.25/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod

| ?- X = 3+2.
X = 3 + 2
yes

Oct-21 p.25/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod
• is operator is required to force evaluation.

| ?- X = 3+2.
X = 3 + 2
yes

Oct-21 p.25/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod
• is operator is required to force evaluation.

| ?- X = 3+2.
X = 3 + 2
yes

| ?- Y is mod(3,4).
Y = 3
yes

Oct-21 p.25/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod
• is operator is required to force evaluation.
• Only right hand side of is is evaluated.

| ?- X = 3+2.
X = 3 + 2
yes

| ?- Y is mod(3,4).
Y = 3
yes

Oct-21 Proo
lg p.25/41
Prolog: Arithmetic

• Arithmetic operators:
+, -, *, /, // (integer division), mod
• is operator is required to force evaluation.
• Only right hand side of is is evaluated.

| ?- X = 3+2.
X = 3 + 2
yes

| ?- Y is mod(3,4).
Y = 3
yes

| ?- 5 is 6 - 1.
yes
| ?- 6 - 1 is 5.
no
Oct-21 p.25/41
Prolog: More Arithmetic

• Comparison operators:
<, =<, >=, >, =:=, =\=

Oct-21 p.26/41
Prolog: More Arithmetic

• Comparison operators:
<, =<, >=, >, =:=, =\=
• Both sides of the operators are evaluated.
| ?- 2+3 < 5+1.
yes

| ?- X < 3+3.
++Error[XSB/Runtime/P]: [Instantiation] Error:
Uninstantiated Arithmetic Expression

| ?- X = 4, X < 3+3.
X = 4
yes

Oct-21 p.26/41
Recursion

• A predicate defined in terms of itself.

Oct-21 p.27/41
Recursion

• A predicate defined in terms of itself.

path(X, Y) :-
edge(X, Y).

path(X, Y) :-
edge(X, Z),
path(Z, Y).

Oct-21 p.27/41
Recursion

• A predicate defined in terms of itself.


ancestor(X, Y) :-
father(X, Y).

ancestor(X, Y) :-
father(X, Z),
ancestor(Z, Y).

Oct-21 p.27/41
Recursion

• Can we also say:


ancestor(X, Y) :-
father(X, Y).

ancestor(X, Y) :-
ancestor(X, Z),
ancestor(Z, Y).

Add a few facts.

father(ram, dashrath).
father(lav, ram).
father(kush, ram).
father(sita, janak).

Try both the versions and report your findings.

Oct-21 p.27/41
Exercise

Write factorial function in Prolog


% factorial (+N, -FN):
% True if FN = N!

Oct-21 p.27/41
Lists

• Intuitively, a collection of data.


• Can be empty or non-empty
• empty list, denoted by []
• non-empty list consists of:
• Head: A Prolog term (may be a list itself!)
• Tail: A list (possiblyempty)
• Single element list has an empty tail.

Oct-21 p.28/41
List Examples

List of integers: [1, 2, 3, 4]


• Head = 1, Tail = [2, 3, 4]

Mixed list: [1, a, ’!@#’, edge(n0, n1)]


• Head = 1, Tail = [a, ’!@#’, edge(n0, n1)]

List of list of characters: [[a,p,p,l,e], [b,a,t], [c,a,t]]


• Head = [a,p,p,l,e], Tail = [[b,a,t], [c,a,t]]

Single element list: [[]]


• Head = [], Tail = []

Oct-21 p.29/41
Lists (Contd. . . )


Most important (Only!) data structure in Prolog

Matching a list: | operator separates a list into its head and tail.
Head/tail matched using prolog matching rules.

| ?- [H | T] = [1,2,3,4].
H = 1
T = [2,3,4]
yes

| ?- [H | [2,3,4]] = [1,2,3,4].
H = 1
yes

| ?- [1 | [X | [3, Y]]] = [1,2,3,4].


X = 2
Y = 4
yes
Oct-21 p.30/41
Working with Lists: Example

% filter odd(+InList, -OddList)


% copies odd numbers from InList to OddList.
%
filter odd([], []).

filter odd([H | TIn], OddList) :-


odd(H),
filter odd(TIn, TOddList),
OddList = [H | TOddList].

filter odd([H | TIn], OddList) :


not(odd(H)),
filter odd(TIn, TOddList),
OddList = TOddList.

Oct-21 p.31/41
Working with Lists

• Typical pattern for processing lists:


◦ Handle the case when list is empty.
◦ Non empty list: Separate the head and the tail.
• Handle the case when head satisfies some property
P.
• Handle the case when head does not satisfy P . In
other words, it satisfies not(P ).
• Handle rest of the list (which is now smaller than the
original list) recursively.
• Note that the pattern makes sure that clauses are mutually
exclusive as well as exhaustive.
• One or more cases may be handled implicitly.

Oct-21 p.32/41
Working with Lists: Example Revisited

% filter odd(+InList, -OddList)


% copies odd numbers from InList to OddList.
%
filter odd([], []).

filter odd([H | TIn], OddList) :-


odd(H),
filter odd(TIn, TOddList),
OddList = [H | TOddList].

filter odd([H | TIn], [H | TOddList]) :-


odd(H),
filter odd(TIn, TOddList).

Oct-21 p.31/41
Working with Lists: Example Revised

% filter odd(+InList, -OddList)


% copies odd numbers from InList to OddList.
%
filter odd([], []).

filter odd([H | TIn], [H | TOddList]) :-


odd(H),
filter odd(TIn, TOddList).

filter odd([H | TIn], TOddList) :-


not(odd(H)),
filter odd(TIn, TOddList).

Oct-21 p.33/41
Working with Lists: Exercise

• Write the following functions:

% member(+Element, +List)
% true if Element belongs to List.

% subset(+Subset, +Set).
% true if Subset is a subset of Set.
% Set and Subset are given as lists.

Oct-21 p.34/41
Working with Lists: Solutions

member(X, [X| ]).


member(X, [ |L]) :-
member(X, L).

subset([], S).
subset([E|Es], S):-
member(E, S),
subset(Es, S).

Oct-21 p.35/41
Working with Lists: Solutions

member(X, [X| ]).


member(X, [ |L]) :-
member(X, L).

subset([], S).
subset([E|Es], S):-
member(E, S),
subset(Es, S).

Note:
• [] case handled implicitly in member.
• member rules not mutually exclusive.
• In subset, case of not(member(E, S)) handled
implicitly.

Oct-21 p.35/41
Working with Lists: Another Example

% filter prime(+InList, -PrimeList)


% copies prime numbers from InList to PrimeList.
%
filter prime([], []).

filter prime([H | TIn], [H | TPrimeList]) :-


prime(H),
filter prime(TIn, TPrimeList).

filter prime([H | TIn], TPrimeList) :-


not(prime(H)),
filter prime(TIn, TPrimeList).

Unnecessary multiple
calls to prime(…)

Oct-21 p.33/41
How to Avoid Unnecessary Duplicate Computation?

• CUT !
• Controls Backtracing
𝐵 → 𝐶% , … , 𝐶&'% , !, 𝐶&(% , … , 𝐶)
• The cut tells control to backtrack past 𝐶&'% , … , 𝐶% , 𝐵 without
considering any remaining rules for them.
• Usage?
• Prune parts of Prolog search that cannot possibly reach a solution

Oct-21 p.36/41
Working with Lists: Another Example

% filter prime(+InList, -PrimeList)


% copies prime numbers from InList to PrimeList.
%
filter prime([], []).

filter prime([H | TIn], [H | TPrimeList]) :-


prime(H), !,
filter prime(TIn, TPrimeList).

filter prime([H | TIn], TPrimeList) :-


filter prime(TIn, TPrimeList).

Oct-21 p.33/41
More Points to Note

• In Prolog, there is no strict classification of arguments as


input or output.

enrolled(X, 5401) gives all courses taken by 5401.

enrolled(cs638, X) gives all students enrolled in cs638.

Oct-21 p.36/41
More Points to Note

• In Prolog, there is no strict classification of arguments as


input or output.
enrolled(X, 5401) gives all courses taken by 5401.
enrolled(cs638, X) gives all students enrolled in
cs638.
• However, for some rules, some arguments act as input,
others as output, some as both.
In powerset(S, PS), typically S is input, and PS output.
In member(E, List), typically List is input. E can be
either input or output.

Oct-21 p.36/41
More Points to Note

• In Prolog, there is no strict classification of arguments as


input or output.
enrolled(X, 5401) gives all courses taken by 5401.
enrolled(cs638, X) gives all students enrolled in
cs638.
• However, for some rules, some arguments act as input,
others as output, some as both.
In powerset(S, PS), typically S is input, and PS output.
In member(E, List), typically List is input. E can be
either input or output.
• Prolog programs may become very confusing and difficult to
understand, if not written properly. It is very important to
follow a good, consistent coding style.

Oct-21 p.36/41
Collecting Solutions

• How to get all solutions to a query? In a neat, usable form.

Oct-21 p.37/41
Collecting Solutions

• How to get all solutions to a query? In a neat, usable form.


• Three builtin predicates:
findall, setof, bagof

Oct-21 p.37/41
Collecting Solutions

• How to get all solutions to a query? In a neat, usable form.


• Three builtin predicates:
findall, setof, bagof
• Compute a list of all solutions to query.

Oct-21 p.37/41
Collecting Solutions: Example

% powerset(+Set, -PowerSet).
% compute Powerset of a Set.
powerset(S, PS) :-
findall(SubS, subset(SubS, S), PS).

Semantics of findall, setof and bagof differ a little.

Oct-21 p.38/41
Topics Not Covered

• I/O, File I/O:


read, write, tell etc
• Storage predicates:
storage insert keypair,
storage delete keypair,
storage find keypair
• Importing/Exporting modules and functions:
import, export, consult
• Debugging:
trace, notrace, spy, nospy

Oct-21 p.40/41
Happy Prologging

Oct-21 p.41/41

You might also like