You are on page 1of 44

Introduction to Artificial Intelligence

(INSY4091)

Lab - 2

1
Basic Elements of Prolog
Programming…
• Build a knowledge base to represent family tree relationships that
can be deduced from the following family tree:
male(abebe). father(abebe,sara).
male(dawit). father(abebe,hailu).
male(hailu). father(dawit,elsa).
male(assefa). father(hailu,rahel).
male(sisay). father(hailu,eden).
male(gobena). father(hailu,assefa).
male(abdi). father(assefa, aster).
male(tariku). father(assefa,sisay).
female(sara). father(gobena,abdi).
female(elsa). father(gobena,tariku).
female(rahel). mother(sara,dawit).
female(eden). mother(aster,gobena).
female(aster). .
.
.
2
Basic Elements of Prolog
Programming…
• A prolog program consists of clauses(facts and rules)
• Each clause terminates with full stop
• The preceding family tree program consists of 25 clauses.
• Each of these clauses declares one fact about the family tree (father,
mother, …).
• For instance, father(abebe, sara) is one instance of the father relation
• Such an instance is also called a relationship.
• A relation is defined as a set of all instances
• The arguments of relations can be concrete objects or constants (such as
abebe, sara, etc) or general objects such as X and Y
• The first kind of objects are called atoms and the second kind of objects
are called variables

3
Basic Elements of Prolog
Programming…
• Questions (queries) to the program consist of one or more goals
• The word ‘goals’ is used because Prolog accepts questions as goals that
are to be satisfied.
• An answer to a question can be either positive or negative, depending on
whether the corresponding goal can be satisfied or not.
• In the case of a positive answer, we say that the corresponding goal was
satisfiable and that the goal succeeded; otherwise, the goal was
unsatisfiable and it failed.
• A question to the system consist of one or more goals
• A sequence of goals such as:
father(X, sara), father(X, hailu).
means the conjunction of the goals:
X is father of sara and
X is father of hailu

4
Basic Elements of Prolog
Programming…
• A prolog predicate can have any number of arguments
• For instance, the facts that ‘abebe gives book to hanna’, ‘abebe
gives book to kebede’ and ‘abebe gives book to aster’ can be
represented as
gives(abebe, book, hanna).
gives(abebe, book, kebede).
gives(abebe, book, aster).
• Here are some possible queries you can make with these
predicates:
1. Who does Abebe give the book to? This query can be satisfied by
the following Prolog goal:
gives(abebe, book, Who).
This returns all the people that Abebe gives the book to.

5
Basic Elements of Prolog
Programming…
2. What does Abebe give to Hanna? This query can be answered by
the following Prolog goal:
gives(abebe, What, hanna).
3. What does Abebe give to everyone? This query can be answered
by the following Prolog goal:
gives(abebe, What, _).
This will return all the people who receive a book from Abebe.
• The underscore character (_) in Prolog is called an anonymous
variable. It is used to represent a variable whose value is not
relevant to the query. Anonymous variables are often used in
Prolog to indicate that a certain argument of a predicate is not
important for the query, or to indicate that a certain argument can
take on any value
6
Basic Elements of Prolog
Programming…
Defining relations by rules
• Considering the traditional context of a parent, i.e. to be a parent
someone has to be either a father or a mother.
• This can be based on the following logical statements:
1. For all X and Y
X is a parent of Y if
X is a father of Y
2. For all X and Y
X is a parent of Y if
X is a mother of Y
• These formulations are already close to Prolog
• The corresponding Prolog clauses are:
parent(X,Y):- father(X,Y).
parent(X,Y):- mother(X,Y).

7
Basic Elements of Prolog
Programming…
• These are called rules
• There is an important difference between facts and rules
• A fact like:
father(abebe, sara). is something that is always unconditionally true; on
the other hand, rules specify things that are true if some condition is
satisfied.
• Therefore, we say that rules have:
– a condition part (the right-hand side of the rule) and
– a conclusion part (the left hand side of the rule)
• the conclusion part is called the head of a clause and the
condition part the body of a clause
• For example:

8
Basic Elements of Prolog
Programming…
• More generally,
A:-B1,B2, … , Bk. (k>=0)
‘:-’ stands for the logical implication ‘’
‘,’ stands for logical conjunction
• A is implied by the conjunction of the Bi’s
• A is called the clause’s head and B’s are called the clause’s body
• If k=0, the clause is changed to a fact and is represented as A.
• Rules are the most important forms of logical statements that
enable us to define new relationships in terms of the existing once

9
Basic Elements of Prolog
Programming…
How rules are used by prolog:
Ex: If we ask Prolog ‘Is Abebe a parent of Sara?’ with the goal:
? parent(abebe, sara).
• There is no fact about parent in the program
• Therefore, the only way to consider this question is to apply the
rule about parent
• The rule is general in the sense that it is applicable to any objects X
and Y
parent(X,Y) :- father(X,Y).
• Therefore, it can also be applied to such particular objects abebe
and sara
• To apply the rule to abebe and sara, X has to be substituted by
abebe and Y by sara 10
Basic Elements of Prolog
Programming…
• We say that the variables X and Y become instantiated to X=abebe
and Y=sara
• After the instantiation, we have obtained a special case of our
general rule
• The special case is - parent(abebe, sara):-father(abebe, sara).
• The condition part has become father(abebe, sara).
• Now, Prolog tries to find out whether the condition part is ture
• So, the initial goal parent(abebe, sara). has been replaced with the
sub goal father(abebe, sara).
• This new goal happens to be trivial as it can be found as a fact in
our program
• This means that the conclusion part of the rule is also true and
Prolog will answer the question with true.

11
Basic Elements of Prolog
Programming…
• Exercises – Write Prolog rules for each of the following
specifications provided as logical statements based on the
above family tree program
1. X is brother of Y if
X is male and
P is parent of X and
P is parent of Y and
X is different from Y (X \== Y).

2. Define a rule for sister relation based on the definition of


brother relation above.
12
Basic Elements of Prolog
Programming…
3. X is a sibling of Y if
X and Y have the same parent (Z is parent of X and Z is parent of Y)
and
X and Y are different

4. X is grandfather of Z if
X is father of Y and
Y is parent of Z

5. Define a rule for grandmother relation based on the above


grandfather relation definition.

13
Basic Elements of Prolog
Programming…
6. X is aunt of Y if
X is female and
X is sibling of Z and
Z is parent of Y

7. Define a rule for uncle relationship based on the above aunt


relation definition.

8. X is niece of Y if
X is female and
Y is sibling of Z and
Z is parent of X

14
Basic Elements of Prolog
Programming…
9. Define a rule for nephew based on the above niece definition.

10. X is cousin of Y if
Z is parent of X and
Z is sibling of W and
W is parent of Y

15
Recursive Rules
• Let us add one more relation to our family tree program –
predecessor
• This relation will be defined in terms of the parent relation
• The whole definition can be expressed with two rules
• The first rule will define the direct(immediate) predecessors and the
second rule the indirect predecessors
• A Prolog clause for the first rule is:
predecessor(X,Z):-
parent(X,Z).
• We say that some X is an indirect predecessor of some Z if there is a
parentship chain of people between X and Z

16
Recursive Rules …
• An elegant and correct formulation of this predecessor relation is:
For all X and Z,
X is a predecessor of Z if
there is a Y such that
(1) X is a parent of Y and
(2) Y is a predecessor of Z.
• A Prolog clause with the above meaning is:
predecessor(X,Z) :-
parent(X,Y),
predecessor(Y,Z).

17
Recursive Rules …
• The complete program that contains both direct and indirect
predecessor rules is:
predecessor(X,Z) :-
parent(X,Z).
predecessor(X,Z) :-
parent(X,Y),
predecessor(Y,Z).
• The key to this formulation was the use of predecessor itself in its
definition.
• Such definitions are, in general, called recursive definitions

18
How Prolog Answers Questions
• A question to Prolog is always a sequence of one or more goals
• To answer a question, Prolog tries to satisfy all the goals
• If the question contains variables, Prolog also has to find what are
the particular objects (in place of variables) for which the goals are
satisfied
• The particular instantiation of variables to these objects is displayed
to the user
• If prolog cannot demonstrate for some instantiation of variables
that the goals logically follow from the program, then Prolog’s
answer to the question will be false
• Let us distinguish the two rules of the predecessor relation(the
direct and indirect) as ‘pr1’ and ‘pr2’

19
How Prolog Answers Questions …
• Given the goal ?-predecessor(aster, tariku)
• Applying rule pr1 we see that parent(aster, tariku) does not hold
because we do not have either the fact father(aster, tariku) or
mother(aster, tariku) in our knowledge base
• By applying rule pr2 as parent(aster, Y) and predecessor(Y, tariku),
we will get that Y=gobena because we have the fact mother(aster,
gobena) in our knowledge base
• Now, applying rule pr1 on predecessor(gobena, tariku), we see that
parent(gobena, tariku) is true because we have the fact
father(gobena, tariku) in our knowledge base
• This will make the sub goal predecessor(gobena, tariku) true which
in turn makes the given goal predecessor(aster, tariku) true

20
How Prolog Answers Questions …
• We have thus shown that our goal statement
predecessor(aster, tariku) is true
• This whole inference process can be written as:
mother(aster, gobena)parent(aster, gobena)
father(gobena, tariku)  parent(gobena, tariku)  predecessor(gobena, tariku)
parent(aster, gobena) and predecessor(gobena, tariku)
predecessor(aster, tariku)
• This is a sequence of steps that satisfy a goal
• We call this a proof sequence
• Prolog finds the proof sequence in the inverse order
• Instead of starting with simple facts given in the program, Prolog starts with
the goals and, using rules, substitutes the current goals with new goals, until
new goals happen to be simplified facts

21
How Prolog Answers Questions …
• Given the question:
?- predecessor(aster, tariku).
• Prolog will try to satisfy this goal
• In order to do so it will try to find a clause in the program which the
above goal could immediately follow
• The only clauses relevant to this end are pr1 and pr2
• These are the rules about the predecessor relation
• We say that the heads of these rules match the goal
• The two clauses, pr1 and pr2, represent two alternative ways for
Prolog to proceed
• Prolog first tries that clause which appears first in the program:
predecessor(X,Z) :- parent(X,Z).

22
How Prolog Answers Questions …
• Since the goal is predecessor(aster, tariku), the variables in the rule
must be instantiated as follows:
X=aster, Z=tariku
• The original goal predecessor(aster, tariku) is then replaced by a
new goal:
parent(aster, tariku)
• This goal in turn is replaced by father(aster, tariku) which results in
false and then Prolog backtracks to parent(aster, tariku) and tries
mother(aster, tariku) which also results in false
• This makes the goal parent(aster, tariku) false
• Therefore, this goal fails
• Now, Prolog backtracks to the original goal in order to try an
alternative way to derive the top goal predecessor(aster, tariku)

23
How Prolog Answers Questions …
• NB:
– Backtracking is a fundamental feature of Prolog that allows it to
explore different possible solutions to a problem
– In simple terms, backtracking means that Prolog will try to
satisfy a goal by finding a rule that matches it, and then try to
satisfy the sub goals of that rule.
– If any sub goal fails, Prolog will backtrack to the previous choice
point and try another alternative, until either all the goals are
satisfied or there are no more alternatives left
• The rule pr2 is thus tried
• As before, the variables X and Z become instantiated as:
X=aster, Z=tariku
• But Y is not instantiated yet

24
How Prolog Answers Questions …
• The top goal predecessor(aster, tariku) is replaced by two goals:
parent(aster, Y),
predecessor(Y, tariku)
• Being now faced by two goals, Prolog tries to satisfy them in the order in
which they are written
• First it replaces the goal parent(aster, Y) by father(aster, Y) which fails
because we do not get such a fact in our knowledge base
• It then backtracks to parent(aster, Y) and tries to replace it by
mother(aster, Y); this time it succeeds because we have the fact
mother(aster, gobena) in our knowledge base; here Y will be instantiated
as Y=gobena
• Then, it backtracks to predecessor(Y, tariku) and replaces Y by gobena and
makes the goal predecessor(gobena,tariku)
• To satisfy this goal the rule pr1 is used again

25
How Prolog Answers Questions …
• Note that this (second) application of the same rule has nothing to do with
its previous application
• To indicate this we shall rename the variables in the rule pr1 for this
application as follows:
predecessor(X’, Z’) : -
parent(X’, Z’).
• The head has to match our current goal predecessor(gobena, tariku)
• Therefore
X’=gobena, Z’=tariku
• The current goal is replaced by parent(gobena, tariku) which is in turn
replaced by father(gobena, tariku)
• This goal is immediately satisfied because it appears in the program as a
fact
• This completes the execution of the trace
• The complete execution trace is illustrated by the following graph
26
How Prolog Answers Questions …

27
How to use SWI Prolog debugging tool
• In order to see the above execution steps on SWI Prolog, you can
use the debugging tool
• To do so, you have to turn the normal mode into trace mode by
using the built-in trace predicate as
?- trace.
• When you press Enter, the prompt changes to
[trace] ?-
• Now you submit your goal and continuously press Enter until it
completes
• You will get the execution traces in the following format

28
How to use SWI Prolog debugging
tool…

29
How to use SWI Prolog debugging
tool…
• The numbers in parentheses indicate the depth of the recursion and the
invocation number of the predicate
• For example, (10) means the depth is 10 and the invocation number is
10. (11) means the depth is 11 and the invocation number is
11. (12) means the depth is 12 and the invocation number is 12, and so on
• The words Call, Exit, Fail, and Redo indicate the different ports that
Prolog visits during the execution
• Call means Prolog is trying to prove a goal
• Exit means Prolog has successfully proved a goal
• Fail means Prolog has failed to prove a goal
• Redo means Prolog is backtracking to find another solution or to
prove another goal.

30
How to use SWI Prolog debugging
tool…
• You can type creep to continue the execution step by step, or
type skip to skip to the next solution, or type abort to abort the
execution, or type help to see other commands
• Creep is the default option that appears at the end of each
execution step and you can continuously press Enter until the
execution completes
• To turn off the trace mode you can use the predefined predicate
called notrace as:
?- notrace.
• When you press Enter, this will take you to:
[debug] ?-
• Here you type the predefined predicate nodebug and press Enter
[debug] ? nodebug.
31
Exercises on Recursive Rules
• Exercises – Write recursive Prolog rules for each of the following
based on the family tree program.
1. Define a rule successor(X,Y) that succeeds if X is successor of
Y. In the context of a family tree, a successor is a person who
is a descendant of another person. For example, if A is a
successor of B, then A is a child, grandchild, great-grandchild,
and so on of B. [hint: use parent]
2. Define a rule ancestor(X,Y) that succeeds if X is an ancestor
of Y. An ancestor is either a parent or a predecessor.
3. Define a rule descendant(X,Y) that succeeds if X is a
descendant of Y. A descendant is a child, grand child, great-
grand child etc.

32
Data Objects/Terms in Prolog
• Prolog programs are built from data objects (or terms)
• There are three types of terms:
– Constants
– Variables
– Structures
• Terms are composed of letters, digits and/or sign characters
• Simple objects:
– constants: for specific objects or specific relationships
• numbers (integers, floating point numbers)
• atoms (bob, hello, *, ‘&?%’, ‘I`m not a variable’)
– variables:
• anonymous variables
• named variables 33
Data Objects/Terms in Prolog…
• Complex objects:
– lists
– other structures
• Variables:
– Names that stand for objects that may already or may not yet
be determined by a Prolog program
• if the object a variable stands for is already determined, the
variable is instantiated
• if the object a variable stands for is not yet determined, the
variable is uninstantiated
– a Prolog variable does not represent a location that contains a
modifiable value; it behaves more like a mathematical variable
(and has the same scope)
34
Data Objects/Terms in Prolog…
• An instantiated variable in Prolog cannot change its value
• Constants in Prolog : numbers, strings that start with lowercase,
anything between single quotes
• Variables in Prolog: names that start with an uppercase letter
or with ‘_’
• Examples:
Variables Constants

X,Y, Var, Const, _var, _const, _ x, y, var, const, some_Thing, 1,


4, ‘String’, “List of ASCII codes”

35
Data Objects/Terms in Prolog…
• Anonymous variables
– a variable that stands in for some unknown object
– stands for some objects about which we don’t care
– several anonymous variables in the same clause need not be
given consistent interpretation
– written as _ in Prolog
– For example, ? mother(X,_) searches for all mothers in the
database

36
Data Objects/Terms in Prolog…
Verify Type of a Term:
• var(+Term) Succeeds if Term is currently a free variable.
• nonvar(+Term) – Succeeds if Term is currently not a free variable.
• integer(+Term) – Succeeds if Term is bound to an integer.
• float(+Term) – Succeeds if Term is bound to a floating point number.
• number(+Term) – Succeeds if Term is bound to an integer or a
floating point number.
• atom(+Term) – Succeeds if Term is bound to an atom.
• string(+Term) – Succeeds if Term is bound to a string.
• atomic(+Term) – Succeeds if Term is bound to an atom, string,
integer or float.
• compound(+Term) – Succeeds if Term is bound to a compound
term.

37
Data Objects/Terms in Prolog…
Structures:
– Structures are objects that have several components, which in
turn can be structures.
– Structures are treated in the program as single objects.
– functor is used to combine components into a single object.
– In Prolog, a functor is a term that consists of an atom and
a fixed number of arguments.
– The atom is the name of the functor, and the arguments are the
terms that follow it
For example, in the term likes(mary, pizza), likes is the functor,
and mary and pizza are the arguments.
The number of arguments is called the arity of the functor
38
Data Objects/Terms in Prolog…
Summary of Data Objects:

39
Logical Connectives (operators) in
Prolog
PL/ FOL Prolog

^ (AND) ,

V (OR) ;

→ (IF) :-

 (NOT) not

40
I/O in Prolog
• Use the write statement:
– Prolog syntax: write(‘hello’).
• Example: write(‘Hello ’), write(‘ World’).
– Use a Newline
• write(‘hello’), nl, write(‘World’).

• Reading a value from stdin


– Prolog Syntax: read(X).
– Example: read(X), write(X).

41
Operators
1. Term comparison operators are used to compare two terms and check if
they are identical or not. The following are the term comparison
operators in Prolog:
a. == : succeeds if the two terms are identical.
b. \== : succeeds if the two terms are not identical.
Ex.
?- X = 5, Y = 5, X == Y.
true.
2. Arithmetic operators are used to perform arithmetic operations on
numbers. The following are the arithmetic operators in Prolog:
+, -, /, //(integer division), mod
Ex.
? X is 5+3. => X=8
? X is 5 mod 3. => X=2
In Prolog, is is an arithmetic operator that is used to evaluate arithmetic
expressions. It is used to assign the value of an arithmetic expression to a
variable. For example, X is 5 + 3 assigns the value of 8 to the variable X 42
Operators…
3. Relational operators are used to compare two values and check if
they are equal, not equal, greater than, less than, greater than or
equal to, or less than or equal to. The following are the relational
operators in Prolog:
Operator Description
=:= Equal to
=/= Not equal to
< Less than
=< Less than or equal to
> Greater than
>= Greater than or equal to
Ex:
• ?- X is 5, Y is 10, X =< Y.
• true. 43
Exercises:
1. Define a predicate that reads a number from the console and
writes its cube to the console.

2. Define a predicate that performs arithmetic operations on


two numbers.

44

You might also like