Vous êtes sur la page 1sur 69

Saved from: www.uotechnology.edu.

iq/dep-cs



1st

Class
Artificial Intelligence Principals

: . .
An I ntroduction to Prolog Language
Definitions of Prolog (programming in logic)
Prolog: is a declarative programming language
In a declarative language
the programmer specifies a goal to be achieved
the Prolog system works out how to achieve it
Prolog: one of the most widely used programming languages in Artificial
Intelligence (AI) research, that is used for solving problems by specifying
the relationships among objects.

Applications of Prolog
The main applications of Prolog are:
intelligent database retrieval
natural language understanding
expert systems (ES)
specification language
machine learning
robot planning
automated reasoning
problem solving

Characteristics of Prolog Language:
1. A particular problem can be solved by using prolog language in less
number of line of code.
2. Its an important tool to develop AI application and ES.
3. Prolog program consist of Fact and Rule to solve the problem and
the output is all possible answer to the problem.
4. Prolog language is a descriptive language use the inference depend
on Fact and Rule which submit to get all possible answer, while in
other language the programmer must tell the computer on how to
reach the solution by gives the instruction step by step.

Data types in prolog
Prolog supports the following data type to define program entries
Integer: to define numerical value like 1, 20, 0,-3,-50, ect.
Real: to define the decimal value like 2.4, 3.0, 5,-2.67, ect.
Char: to define single character, the character can be of type small
letter or capital letter or even of type integer under one condition it
must be surrounded by single quota. For example, a,C,123.
string: to define a sequence of character like good i.e. define word
or statement entries the string must be surrounded by double quota for
example computer, 134, a. The string can be of any length and
type.
Symbol: another type of data type to define single character or
sequence of character but it must begin with small letter and dont
surround with single quota or double quota.
Atoms: Any name that starts with a lowercase letter (followed by
zero or more additional letters, digits, or underscores) is an atom.
Sequences of most non-alphanumeric characters (+, *, -, etc.) are
also atoms.
Variables: A variable is any name beginning with an uppercase
letter or an underscore, followed by zero or more additional letters,
digits, or underscores.
For example: X, Y, Variable, _tag, X_526, List, List24, _head,
Tail, _input and Output are all Prolog variables.

Program Structure
Prolog program structure consists of five segments, not all of them must
appear in each program. The following segment must be included in each
program predicates, clauses, and goal.

1. Domains: define global parameter used in the program. Like
Domains
I= integer
C= char
S = string
R = real
2. Data base: define internal data base generated by the program
Database, like
Greater (integer)
3. Predicates: define rule and fact used in the program, like
Predicates
Mark(symbol,integer).
4. Clauses: Predicate definitions consist of clauses. It is an individual
definition (whether it is a fact or rule).
mother(jane,alan). Fact
parent(P1,P2):- mother(P1,P2). Rule
A clause consists of a head and sometimes a body. Facts dont have
a body because they are always true. A predicate head consists of a
predicate name and sometimes some arguments contained within
brackets and separated by commas. mother(jane, alan).
5. Goal: can be internal or external, internal goal written after clauses
portion, external goal supported by the prolog compiler if the
program syntax is correct. This portion contains the rule that drive
the program execution.

Programming in Prolog
Declaring some facts about object and their relationships.
Defining some rules about objects and their relationships.
Asking questions about objects and their relationships

So, prolog language can be considered as a store house of facts and rules,
and it uses the facts and rules to answer questions.

Basic Elements of Prolog
1. Facts.
2. Rules.
3. Questions.

1. Facts
Facts are the relationships between objects. When writing Fact must
notice the following points:
Names of relationships begin with lowercase letters.
The relationship name appears as the first term.
Objects appear as comma-separated arguments within parentheses.
A period "." must end a fact.
Objects also begin with lowercase letters.
For Example
"John likes football"
likes(john, football).
The names of objects that are enclosed within the round brackets are
called arguments, and the name of relationship called predicates.
Relationship has arbitrary number of argument. For example "John
and Mary play football" play can be defined as a predicate, two
players (John and Mary) and a game (football) play with each other,
it can be:
play(john, mary, football).

2. Rules
Rule consists of a head (a predicate) and a body (a sequence of predicates
separated by commas). The word if used after the head and represented as
:- which separates the Head and body, like every Prolog expression, a
rule has to be terminated by a dot.
To build a rule, head can be represented as conclusion and body can be
represented as condition. The syntax of if statement
If (condition) then (conclusion)
[conclusion :- condition]. rule

For Example:
It will rain if the sky is cloudy
conclusion condition
represent both as fact like:
wheatear(rain).
cloudy(sky).
wheatear(rain) :- cloudy(sky). Rule

3. Questions
Question used to ask about facts and rules. Question look like the fact and
written under the goal program section while fact and rule written under
clauses section.
For Example: the following fact
owns(mary, book).
to ask: "dose mary own the book" in the following manner:
Goal: ?-owns(mary, book).
When Question is asked in prolog, it will search through the database you
typed before, it look for facts that match the fact in the question. Two fact
matches if their predicates are the same and their corresponding argument
are the same, if prolog finds a fact that matches the question, prolog will
respond with Yes, otherwise the answer is No.

Type of questing in the goal
There are three type of question in the goal summarized as follow:
1. Asking with constant: prolog matching and return Yes/No answer.
2. Asking with constant and variable: prolog matching and produce result
for the variable.
3. Asking with variable: prolog produce result.
For Example:
age(a,10).
age(b,20).
age(c,30).
Goal:
1. ?-age(a, X). answer: X=10 (Type2)
2. ?-age(X, 20). answer: X=b (Type2)
3. ?-age(X, Y). answer: X=a Y=10, X=b Y=20, X=c Y=30. (Type3)
4. ?-age(_, X). answer: X=10 , X=20, X=30. (Type3)
_ means dont care
5. ?-age(_, _). answer: Yes (Type1)

Example of Facts:
John is the father of Jim. father(john, jim).
Jane is the mother of Jim. mother(jane, jim).
Jack is the father of John. father(jack, john).

Example of Rules:
Person1 is a parent of Person2 if Person1 is the father of Person2
or Person1 is the mother of Person2.
parent(person1,person2):- father(person1,person2);
mother(person1,person2).
Person1 is a grandparent of Person2 if Person3 is a parent of
Person2 and Person1 is a parent of Person3.
grandparent(person1,person2):- parent(person3,person2),
parent(person1,person3).

Example of Questions:
Who is Jim's father? ?- father(who, jim).
Is Jane the mother of Fred? ?- mother(jane, fred).
Is Jane the mother of Jim? ?- mother(jane, jim).
Does Jack have a grandchild? ?- grandparent(jack, _).

Mathematical and Logical Operation
a .mathematical operation:
Operation Symbol
addition +
subtraction
multiplication *
Integer part of division div
Remainder of division mod

B .logical operation
Operation Symbol
greater >
Less than <
Equal =
Not equal <>
Greater or equal >=
Less than or equal <=

Other mathematical function
Function name operation
Cos(X) Return the cosine of its argument
Sin(X) Return the sine of its argument
Tan(X) Return the tangent of its argument
Exp(X) Return e raised to the value to which
X is bound
Ln(X) Return the natural logarithm of X
(base e)
Log(X) Return the base 10 logarithm of log
10
x

Sqrt(X) Return the positive square of X
Round(X) Return the rounded value of X.
Rounds X up or down to the nearest
integer
Trunc(X) Truncates X to the right of the
decimal point
Abs(X) Return the absolute value of X

Example: Write a prolog program that take two numbers as integer and
print the greater.

Domains
I = integer
Predicates
greater ( i,i)
Clauses
greater(X,Y):- X>Y,write(the greater is,X).
greater(X,Y):- write ( the greater is ,Y).

Goal: greater(4,3).
Output: The greater is 4


Recursion
The recursion in any language is a function that can call itself until the
goal has been succeed. In Prolog, recursion appears when a predicate
contain a goal that refers to itself. There are two types of recursion:
Tail Recursion: is recursion in which the recursive call is always
made just in the last step before the procedure exits.
For Example: Write a prolog program to find the factorial of 5! =
5*4*3*2*1

Domains
I= integer
Predicates
fact( I, I, I)
Clauses
fact(1, F, F):-!.
fact(N,F,R):- F1=F*N , N1=N-1, fact(N1,F1,R).

Goal: fact(5,1,F).
Output: F = 120

Non Tail Recursion: is recursion in which the recursive call is not
the last step in the procedure.
For Example: Write a prolog program to find the factorial of 5! =
5*4*3*2*1

Domains
I= integer
Predicates
Fact ( I, I, I)
Clauses
fact(1, 1):-!.
fact(N,F):- N1=N-1, fact(N1,F1), F=N*F1.

Goal: fact(5,F).
Output: F = 120

Conjunctions and Backtracking
1. Conjunctions
and ,
or ;
Used to combine facts in the rule, or to combine fact in the goal to answer
questions about more complicated relationship.

Example:
Facts
like (mary,food(.
like(mary,wine(.
like(john,mary(.

Goal: like(mary,john),like(john,mary).

it can ask dose mary like john and dose john like mary?
Now, how would prolog answer this complicated question?
Prolog answers the question by attempting to satisfy the first goal. if the
first goal is in the database, then prolog will mark the place in the
database, and attempt to satisfy the second goal.
If the second goal is satisfied, then prolog marks that goals place in the
database, and have a solution that satisfy both goals.
It is important to remember that each goal keeps its own place marker. If,
however, the second goals are not satisfied, then prolog will attempt to re-
satisfy the previous goal.
Prolog searches the database in case it has to re-satisfy the goal at a later
time. But when a goal needs to be re-satisfied, prolog will begin the
search database completely for each goal. If a fact in the database
happens to match, satisfying the goal, then prolog will mark the place in
the database in case it has to re-satisfy the goal at the later time. But when
a goal needs to be re-satisfied, prolog will begin the
search from the goals own place marker, rather than from the start of
database and this behavior called backtracking.

Example about the Backtracking
Facts
like(mary,food).
like(mary,wine).
like(john,wine).
like(john,mary).

Goal: like(mary,X),like(john,X).

, like(john,X)

X=food
like(mary ,food).
like(mary,wine).
like(john,wine).
like(john,mary)
1. The first goal succeed, bound X to food.
2. Next, attempt to satisfy the second goal.
like(mary,X)

,

X=food
like(mary ,food).
like(mary,wine).
like(john,wine).
like(john,mary

3. The second goal fails.
4. Next, backtrack: forget previous value of X and attempt to resatisfy the
first goal.


, like(john,X)

X=wine
like(mary ,food).
like(mary,wine).
like(john,wine).
like(john,mary)

5. The first goal succed agin, bund X to wine.
6. Next, attempt to satisfy the second goal.





like(mary,X) like(john,X)
like(mary,X)

,

X=wine

like(mary ,food).
like(mary,wine).
like(john,wine).
like(john,mary)
7. The second goal succeeds.
8. Prolog notifies you of success.

Cut Function
The Prolog cut adds an 'else' to Prolog. Sometimes it is desirable to
selectively turn off backtracking. Prolog provides a predicate that
performs this function. It is called the cut, represented by an exclamation
point .)!(
The cut effectively tells Prolog to freeze all the decisions made so far in
this predicate. That is, if required to backtrack, it will automatically fail
without trying other alternatives.

For Example: program using cut.
Domains
I= integer
Predicates
no( I )
Clauses
no (5):-!.
like(mary,X) like(john,X)
no (7).
no (10).

Goal: no (X).
Output: X=5.

For Example: using cut in the end of the rule.
Domains
I =integer
S = symbol
Predicates
a(I )
b (S )
c (I, S )
Clauses
a(10).
a(20)
b(a)
b(c)
c (X, Y):- a (X), b (Y),!.

Goal: c(X,Y).
Output: X= 10 Y=a




For Example: using cut in the middle of the rule.
Domains
I =integer
S = symbol
Predicates
a(I )
b (S )
c ( I, S )
Clauses
a(10).
a(20)
b(a)
b(c)
c (X, Y):- a (X),!, b (Y).

Goal: c(X,Y).
Output: X= 10 Y=a
Y=c

Fail Function
The fail predicate is provided by Prolog. When it is called, it causes the
failure of the rule. And this will be forever; nothing can change the
statement of this predicate.
The fail function is used to enforce backtracking, place always in the end
of rule, produce false and can be used with internal goal to produce all
possible solution.


For Example:
Domains
I=integer
Predicates
a(I)
begin
Clauses
a(1).
a(2).
a(3).
a(4).
begin:-a(X),write(X),fail.

Goal: begin
Output: 1234 NO

For Example:
Domains
I=integer
Predicates
a(I)
begin
Clauses
a(1).
a(2).
a(3).
a(4).
begin:-a(X),write(X),fail.
begin.

Goal: begin
Output: 1234 yes

Complete Prolog Programs
Write a prolog program to sum two numbers. (this program can be
solved in 3 ways)
Domains
I=integer
Predicates
Sum(I,I,I)
Clauses
Sum(X,Y,Sum):- Sum = X+Y.

Goal: Sum(3,5,S)
Output: S=8

Domains
I=integer
Predicates
Sum(I,I)
Clauses
Sum(X,Y):-Sum=X+Y, write(Sum).

Goal: sum(3,5)
Output: 8

Predicates
Sum
Clauses
Sum:-readint(X),readint(Y),Sum=X+Y, write(Sum).

Goal: sum
Output: 8

Write a prolog program to count numbers from 1-10.
Domains
I=integer
Predicates
counter(I)
Clauses
counter(10):-!.
counter(X):-write(X), X1=X+1, counter(X1).

Goal: counter(1)
Output: 1 2 3 4 5 6 7 8 9

Write a prolog program to sum 10 numbers
Domains
I=integer
predicates
sum(I,I,I)
clauses
sum(10,S,S):-!.
sum(X,Y,S):-Y1=Y+X,X1=X+1,sum(X1,Y1,S),!.

Goal: sum(1,0,M)
Output: ?

Write a prolog program to read integer number and print it.
Domains
I = integer
Predicates
print.
Clauses
Print:- write (please read integer number), readint(X),
write(you read,X).

Goal: Print.
Output: Please read integer number 4
You read 4

Write a prolog program to find the power of any number using tail
recursion
Domains
I=integer
Predicate
power(I,I,I,I)
Clauses
power(_,0,P,P):-!.
power(X,Y,Z,P):-Z1=Z*X,Y1=Y-1,power(X,Y1,Z1,P),!.

Goal: power(5,2,1,P)
Output: P=25

Write a prolog program to find the power of any number using
nontail recursion
Domains
I=integer
Predicate
power(I,I,I)
Clauses
power(_,0,1):-!.
power(X,Y,P):-Y1=Y-1,power(X,Y1,P1),P= P1 *X.

Goal: power(5,2,P)
Output: P=25

Repetition
In prolog there is a constant formula to generate repetition; this technique
can generate repetition for some operation until the stopping condition
become true.

For Example: Write a prolog program to read and write a number of
characters continue until the input character equal to #.

Predicates
Repeat.
Typewriter.
Clauses
Repeat.
Repeat:-repeat.
Typewriter:-repeat,readchar(C),write(C ),nl,C=#,!.

Lists in Prolog
In prolog, a list is an object that contains an arbitrary number of objects
within it and that can have any length. A list is either empty or it is a
structure that has two components: the head H and tail T.

Syntax of List
List always defined in the domains section of the program as follow:
Domains
list = integer*
* refer to list object which can be of length zero or undefined.
The type of element list can be of any standard defined data type
like integer, char etc.
List element surrounded with square brackets and separated by
comma as follow: l = [1, 2, 3, 4].
List consist of two parts head and tail, the head represent the first
element in the list and the tail represent the remainder (i.e. head is
an element but tail is a list). for the following list :
L = [1,2,3]
H = 1 T =[2,3]
H =2 T =[3]
H =3 T=[ ]
[ ] refer to empty list.
List can be written as [H|T] in the program, if the list is non empty then
this statement decompose the list into Head and tail otherwise ( if the list
is empty) this statement add element to the list.

For Example: write a prolog program to input integer numbers in the list.
Domains
L=Integer*.
I=Integer
Predicates
Input(I,L)
Clauses
Input(0,[]):-!.
Input(N,[H|T]):-readint(H),N1=N-1,Input(N1,T).

Goal: Input(5,L)
2
3
5
7
9
Output: L=[2,3,5,7,9]

For Example: write a prolog program to print the contents of the list.
Domains
L=integer*
Predicates
print(L)
Clauses
print([]).
print([H|T]):-write(H),print(T).

Goal: print([3,4,5])
Output: 345yes

For Example: write a prolog program to append two lists.
Domains
L=integer*
Predicates
app(L,L,L)
Clauses
app([],L,L).
app([H|T1],L2,[H|T3]) :-app(T1,L2,T3).

Goal: app([3,4,5],[6,7,8],L)
Output: L=[3,4,5,6,7,8] yes

For Example: write a prolog program to spilt a list into a positive list
numbers and a negative list numbers.
Domains
L= integer*
Predicates
Spilt ( L,L,L)
Clauses
Spilt ( [ ],[ ],[ ]):-!.
Spilt ( [H| T],[H|T1],L2):- H>= 0,!,Spilt (T, T1,L2).
Spilt ([H|T],L1,[H|T2] ):-Spilt ( T,L1,T2).

Goal: Spilt ([-1, 4,-9, 8, 0], L1, L2).
Output: L1 = [4,9,0]
L2 = [-1,-9]

For Example: write a prolog program to find the maximum value of the
list.
Domains
L=integer*
I=integer
Predicates
Max (L,I,I)
Clauses
Max([],M,M):-!.
Max([H|T],X,M):-H>X,!,Max(T,H,M).
Max([_|T],X,M):-Max(T,X,M).

Goal: Max ([3,9,4,5],0,M)
Output: M=9 yes

For Example: Write prolog program that delete a specified element in a
list.
Domains
I=integer
L=integer*
Predicates
Delete(L,I,L)
Clauses
Delete([],_,[]):-!.
Delete([H|T],H,L):- Delete(T,H,L),!.
Delete([X|T],H,[X|T2]):- Delete (T,H,T2).

Goal: Delete([2,5,7,8,7],7,L)
Output: L=[2,5,8]

For Example: write a prolog program to find the sum of integer list.
Domains
I= integer
L= integer *
Predicates
Sum ( L, I, I)
Clauses
Sum ([ ],S,S):-!.
Sum( [H| T],S1,S):- S2 = S1+H , Sum (T,S2,S).

Goal: Sum ( [ 1,4,6,9],0 ,S).
Output: S = 20



List Membership
Member is possibly the most used user-defined predicate (i.e. you have
to define it every time you want to use it!). It checks to see if a term is an
element of a list.
it returns yes if it is.
and fails if it isnt.

member(X,[X|_]):-!.
member(X,[_|Y]) :- member(X,Y).

It 1st checks if the Head of the list unifies with the first argument.
If yes then succeed.
If no then fail first clause.
The 2nd clause ignores the head of the list (which we know doesnt
match) and recourses on the Tail.

For Example: write a prolog program to check if a given integer number
is membership of a list or not.
Domains
I=integer
L=integer*
Predicates
Member(I,L)
Clauses
Member(X,[X|_]):-!.
Member(X,[_|Y]) :- Member(X,Y).

Goal: Member(a, [b, c, a]).
Output: Yes
Or if
Goal: Member(a, [c, d]).
Output: No.

For Example: write a prolog program to union of two lists.
Domains
I=integer
L=integer*
Predicates
Union(L,L,L)
Member(I,L)
Clauses
Union([],L,L):-!.
Union([H|T],L1,L):-Member(H,L1),!,Union(T,L,L).
Union([H|T],L.[H|T1]):-Union(T,L1,T1).
Member(X,[X|_]):-!.
Member(X,[_|Y]) :- Member(X,Y).

Goal: Union ([2,4,1,5],[2,3,4,5,6],L).
Output: L=[2,4,1,5,3,6]

Homework
Write a prolog program to find the intersection between two lists.
Write a prolog program to find the difference between two lists.
Write a prolog program to find the length of a list.
Write a prolog program that sort a list descending.
Write a prolog program to find the factorial for each number in
the list.
Write prolog program that sort a list descending.
Write prolog program to get the element at nth index lists.
Write prolog program that take two lists as input and produce a
third list as output, this list is the sum of the two lists.
Write prolog program that multiply each element in the list by 5.

Standard String Predicates
Prolog provides several standard predicates for powerful and efficient
string manipulations. This section summarizes the standard predicates
available for string manipulating and type conversion.

str_len (String,Length) (string,integer): Determines the length of
String.
str_len(prolog,X)
X=6.
str_int (String,Int) (string,integer): Converts a string of one
character to ASCII code or vice versa.
str_int(A,X)
X=65.
char_int (Char,Int) (char,integer): Converts a character to ASCII code
or vice versa.
char_int(A,X)
X=65.
Str_char(string,char): convert the string (of one char) to char and the
opposite.
Str_char("A",X)
X='A'
Str_char(X,'A')
X="A"
Isname (string): test if the content of the string is name or not
isname(s2) return YES.
isname(4r) return NO.
frontchar (String,Char,RestString) (string,char,string): Extracts the
first character from a string, the remainder is matched with Rest
String.
frontchar (prolog,C,R)
C=p, R=rolog.
fronttoken (String,Token,RestString) (string,string,string): Skips all
white space characters (blanks, tabs) and separates from the resulting
string the first valid token. The remainder is matched with Rest String.
fronttoken (complete prolog program,T,R)
T=complete, R=prolog program.
frontstr (StrLen,String,FrontStr,RestStr): Extracts the first n
characters from a string. This establishes a relation between String,
Count, FrontStr, and Rest String, thus that String =
FrontStr+RestString and str_len(FrontStr,Count) is true. The String
and Count arguments must be initialized.
frontstr(3,cdab2000,T,R)
T=cda, R=b2000.
concat (Str1,Str2,ResStr) (string,string,string): Concat two string
together to produce one string.
concat (prolog,2011,R)
R=prolog2011.
Upper_lower (string,string): Convert the string in upper case (in
capital letter) to the lower case (small letter) and the opposite.
Upper_lower(capital_letter,small_letter)
Upper_lower("ABC",X)
X="abc"
Upper_lower("Abc",X)
X="abc"
Upper_lower(X,"abc")
X="ABC"

For Example: write a prolog program to convert the string of words into
a list of words.
Domains
L=string*
S=string
Predicates
split(S,L)
Clauses
split("",[]).
split(S,[H|T]):-fronttoken(S,H,R),split(R,T).

Goal: split("list of words",L)
Output: L=["List","of","words"]

For Example: write a prolog program to convert the string into a list of
characters.
Domains
L=char*
S=string
Predicates
split(S,L)
Clauses
split("",[]).
split(S,[H|T]):-frontchar(S,H,R),split(R,T).

Goal: split("abc",L)
Output: L=['a','b','c']

For Example: write a prolog program that read two string and concat
them in one string as upper case.
Predicates
start(string)
Clauses
start(X):-readln(S),readln(S1),concat(S,S1,S2),upper_lower(X,S2).

Goal: start(X)
Output: Ahmed
Ali
X=AHMEDALI yes

For Example: write a prolog program that take a string of words and
print each word in a line as upper case.
Predicates
start(string).
Clauses
start(S):-fronttoken(S,S3,S2), upper_lower(S1,S3), write(S1), nl,start(S2).
start("").

Goal: start("ali is a good boy").
Output:
ALI
IS
A
GOOD
BOY
yes

For Example: write a prolog program that take a string and convert each
character it contains to its corresponding integer value.
Predicates
start(string).
Clauses
start(S):-frontchar(S,S3,S2), char_int(S3,I), write(I), nl , start(S2).
start("").

Goal: start("abc").
Output:
97
98
99
Yes

For Example: write a prolog program that returns the number of names
in a specific string.
Predicates
start(string,integer).
Clauses
start(S,X):-fronttoken(S,S1,S2),isname(S1),X1=X+1,start(S2,X1).
start(S,X):-fronttoken(S,_,S2),start(S2,X).
start("",X):-write("the number of names is", X).

Goal: start("ali has 2 cars",X).
Output: The no. of names is 3 Yes

For Example: write a prolog program that split a specific string to small
string with length 3 char.
Predicates
start(string).
Clauses
start("").
start(S):-frontstr(3,S,S1,S2), write(S1), nl,start(S2).
start(S):-concat(S," ",S1),start(S1).

Goal: start("abcdefg").
Output:
abc
def
g
yes

For Example: write a prolog program to convert a list of words into
string.
Domains
L=string*
S=string
Predicates
Change(L,S)
Clauses
Change([], ):-!.
Change([H|T],S):-change(T,S1), concat(H,S1,S).

Goal: Change(["List","of","words"],S)
Output: S="List of words"

For Example: write a prolog program to convert a list of characters into
string.
Domains
L=char*
S=string
Predicates
Change(L,S)
Clauses
Change([], ):-!.
Change([H|T],S):-change(T,S1), str_char(S2,H), concat(S2,S1,S).

Goal: Change(['w','o','r','d'],S)
Output: S="word"

Homework
write a prolog program to read a string and find the following:-
1. How many characters in the string.
2. How many words in the string.
3. How many sentences in the string.
4. Find the longest word in the string.
write a program to count the number of words that length one
character or two characters or three characters.
write a program to count the number of vowel characters in a
string.
write a program to count the number of words in string.
write a program to count the number of characters in string.
perform the following:-
["dictionary","symbol","intelligence",.......]
[10,7,12,........]
Write a prolog program that do the following: convert the string
such as "abcdef" to 65 66 67 68 69 70.
Write a prolog program to find the number of tokens and the
number of characters in a specific string such as: "abcdef" the
output is one token and 6 characters.
Artificial Intelligence
Artificial intelligence (AI) is an area of computer science that emphasizes
the creation of intelligent machines that work and react like humans.
Some of the activities computers with artificial intelligence are designed
for include speech recognition, learning, planning and problem solving.

Knowledge Representation
Many of the problems machines are expected to solve will require
extensive knowledge about the world. Among the things that AI needs to
represent are: objects, properties, categories and relations between
objects; and many other. There are many methods can be used for
knowledge representation and they can be described as follows:-
1. Propositional Logic
2. Predicate Logic
3. Clauses Form
4. Semantic Network
5. Conceptual Graph
6. Frame Representation

1. Propositional Logic (calculus)

Truth symbols: true, false
Propositional symbols: P, Q, S, ... (atomic sentences)
Wrapping parentheses: ( )
Sentences are combined by connectives:
...and [conjunction]
...or [disjunction]
...implies [implication / conditional]
. .is equivalent [biconditional]
...not [negation]


Examples
(P Q) ( Q P)
P Q
PQ
Q QP
(PQ)(QP)
T T T F T T
T F F T T T
F T F F F F
F F F T T T

AB AB
A B AB A AB
T T T F T
T F F F F
F T T T T
F F T T T


Homework:
1. a(bc)(ab)(ac)
2. a(bc)(ab)(ac)

It is hot
p

It is not hot
p

If it is raining, then will not go to mountain
p q

The food is good and the service is good

x y

If The food is good and the service is good then the restaurant is good
x y z

The prepositional calculus has its limitations that you cannot deal properly
with general statements because it represents each statement by using some
symbols jointed with connectivity tools.

Homework
Proofs in propositional logic the following sentences.
If it is sunny today, then the sun shines on the screen. If the sun shines on
the screen, the blinds are brought down. The blinds are not down.
Is it sunny today?

Predicate Logic (Calculus)
To solve the limitations in the prepositional calculus, you need to analyze
propositions into predicates and arguments, and deal explicitly with
quantification. Predicate Logic provides a formalism for performing this
analysis of prepositions and additional methods for reasoning with
quantified expressions.

Examples
If it is raining, tom will go to mountain
rain(weather)go(tom,mountain)

All basketball players are tall
X play(X, basketball)tall(X)

John like anyone who likes books
like(X,book)like(john,X)

Nobody likes taxes
X likes(X,taxes)

There is a person who write computer class
X write(X,computer class)

All dogs are animals
X dogs(X)animals(X)

John did not study but he is lucky
study(john)luky(john)

All cats and dogs are animals
XY cats(X)dogs(Y)animals(X)animals(Y)

Predicate Logic with clauses form
Steps to convert a sentence to clause form:
1. Eliminate all () by replacing each instance of the form (P Q)
by expression (PQ)
2. Reduce the scope of negation.
(a)a
(X) b(X)X b(X)
(X) b(X)X b(X)
(ab)ab
(ab)ab
3. Standardize variables: rename all variables so that each quantifier
has its own unique variable name. For example,
X a(X) X b(X) X a(X) Y b(Y)
4. Move all quantifiers to the left without changing their order. For
example,
X a(X) Y b(Y)
X Y a(X) b(Y)
5. Eliminate existential quantification by using the equivalent function.
For example,
X Y (mother(X,Y)) X (mother(X,m(X)))
X Y Z W (food(X,Y,Z,W) X Y W
(food(X,Y,f(X,Y),W)
6. Remove universal quantification symbols.
7. Distribute "and" over "or" to get a conjunction of disjunctions called
conjunctive normal form. For example,
a(bc)(ab)c
a(bc)(ab)c
a(bc)(ab)(ac)
a(bc)(ab)(ac)
8. Split each conjunct into a separate clause. For example,
a(X) b(X)e(W)b(X)d(X,f(X))e(W)
a(X) b(X)e(W)
b(X)d(X,f(X))e(W)
9. Standardize variables apart again so that each clause contains variable
names that do not occur in any other clause. For example,
a(X) b(X)e(W)b(X)d(X,f(X))e(W)
a(X) b(X)e(W)
b(Y)d(X,f(X))e(V)

Example for Predicate Logic with clauses form

Everyone passing their AI exam and winning the lottery is happy. But
everyone who studies or lucky can pass all their exams, John did not study
but he is lucky. Everyone who is lucky wins the lottery. Prove that John is
happy.

X pass(X,AI exam)win(X,lottery)happy(X)
YE study(Y)lucky(Y)pass(Y,E)
study(john)lucky(john)
Z lucky(Z)win(Z,lottery)
happy(john)?
1.
X (pass(X,AI exam)win(X,lottery)) happy(X)
YE (study(Y)lucky(Y)) pass(Y,E)
study(john)lucky(john)
Z (lucky(Z)) win(Z,lottery)
happy(john)?
2.
X (pass(X,AI exam)win(X,lottery)) happy(X)
YE ) study(Y)lucky(Y)) pass(Y,E)
study(john)lucky(john)
Z lucky(Z)win(Z,lottery)
happy(john)?
3. Nothing to do here.
4. Nothing to do here.
5. Nothing to do here.
6.
) pass(X,AI exam)win(X,lottery)) happy(X)
) study(Y)lucky(Y)) pass(Y,E)
study(john)lucky(john)
lucky(Z)win(Z,lottery)
happy(john)?
7.
pass(X,AI exam)win(X,lottery) happy(X)
) study(Y)lucky(Y)) pass(Y,E) (ab)cc(ab)
The second statement become pass(Y,E)study(Y)pass(Y,E)lucky(Y)
study(john)lucky(john)
lucky(Z)win(Z,lottery)
happy(john)?
8.
pass(X,AI exam)win(X,lottery) happy(X)
pass(Y,E)study(Y)
pass(Y,E)lucky(Y)
study(john)
lucky(john)
lucky(Z)win(Z,lottery)
happy(john)?
9.
pass(X,AI exam)win(X,lottery) happy(X)
pass(Y,E)study(Y)
pass(M,G)lucky(M)
study(john)
lucky(john)
lucky(Z)win(Z,lottery)
happy(john)?

Proving happy(john) using Backward Resolution
Notes
resolution .
.fact

happy(john)

happy(john)
pass(X,AI exam)win(X,lottery) happy(X)
X=john
pass(X,AI exam)win(X,lottery)
lucky(Z)win(Z,lottery)
Z=X
pass(X,AI exam)lucky(Z)
lucky(john)
Z=john
pass(X,AI exam)
pass(M,G)lucky(M)
G=AI exam, M=X
lucky(M)
lucky(john)
M=john
John is happy

Proving happy(john) using Forward Resolution

pass(X,AI exam)win(X,lottery) happy(X)
lucky(Z)win(Z,lottery)
Z=X
pass(X,AI exam) happy(X) lucky(Z)
lucky(john)
Z=john
pass(X,AI exam) happy(X)
pass(M,G)lucky(M)
M=X, G= AI exam
happy(X) lucky(M)
lucky(john)
M=john
happy(X)
happy(john)
X=john

Example
All people that are not poor and smart are happy. Those people that read are
not stupid. John can read and wealthy. Happy people have exciting life. Can
anyone found with an exciting life.

X(poor(X)smart(X))happy(X)
read(Y) stupid(Y)
read(john) wealthy(john)
happy(Z) exciting(Z,life)
W exciting(W,life)

Note stupid smart, wealthypoor

X(poor(X)smart(X))happy(X)
read(Y)smart (Y)
read(john) poor(john)
happy(Z) exciting(Z,life)
W exciting(W,life)

1.
X (poor(X)smart(X)) happy(X)
read(Y)smart(Y)
read(john) poor(john)
happy(Z) exciting(Z,life)
W exciting(W,life)
2.
X (poor(X)smart(X)) happy(X)
read(Y)smart(Y)
read(john) poor(john)
happy(Z) exciting(Z,life)
W exciting(W,life)
3. Nothing to do here.
4. Nothing to do here.
5.
X (poor(X)smart(X)) happy(X)
read(Y)smart(Y)
read(john) poor(john)
happy(Z) exciting(Z,life)
exciting(W,life)
6.
(poor(X)smart(X)) happy(X)
read(Y)smart(Y)
read(john) poor(john)
happy(Z) exciting(Z,life)
exciting(W,life)
7. Nothing to do here.
8.
poor(X)smart(X) happy(X)
read(Y)smart(Y)
read(john)
poor(john)
happy(Z) exciting(Z,life)
exciting(W,life)
9. Nothing to do here.

Proving exciting(W,life)using Backward Resolution
exciting(W,life)

exciting(W,life)
happy(Z) exciting(Z,life)
Z=W
happy(Z)
poor(X)smart(X) happy(X)
X=Z
poor(X)smart(X)
read(Y)smart(Y)
Y=X
poor(X) read(Y)
poor(john)
X=john
read(Y)
read(john)
Y=john

Proving exciting(W,life)using Forward Resolution

poor(X)smart(X) happy(X)
read(Y)smart(Y)
X=Y
poor(X) happy(X) read(Y)
read(john)
Y=john
poor(X) happy(X)
happy(Z) exciting(Z,life)
Z=X
poor(X) exciting(Z,life)
exciting(W,life)
W=Z
poor(X)
poor(john)
X=john


Homework
Everyone has a parent. The parent of a parent is a grandparent. Prove that
Ali has a grandparent using Backward Resolution.


3. Semantic Network
A semantic net is a labeled directed graph, where each node represents an
object (a proposition), and each link represents a relationship between two
objects.

Examples
John broke the window with the hummer











John gave mary a book of data structure in the class









broke
john
window
hummer
agent
object
instrument
gave
john
class
past
agent
location
time
book
object
mary
data
structure
type
recipient
Tom think that john like football












The emma dog scratches it's ear with its paw














like
john present
agent
time
football
object
think
propositional
tom
time
scratches
dog
present
agent
time
paw
ear
instrument

emma
name
object
part of
part of
agent
Birds and fish are animals. Birds are moving by fly and they lay
eggs. They have wings and their active at day light. kiwi and
alberto are birds. The color of kiwi is black and white and the color
of alberto is brown. Fish moves by swimming and has a skin.















5. Conceptual Graph
A conceptual graph consists of concept nodes and relation nodes.
a. The concept nodes represent entities, attributes, states, objects and
events.



b. The relation nodes show how the concepts are interconnected.


is-a
black and
white
move
swimming
animals fish birds
skin
has
kiwi
day light
is-a
is-a
active
have move
lay
color
Wings fly
eggs
alberto
is-a
brown
color
Examples
A dog has a color of brown







A child has as parents, a father and a mother








The dog scratches its ear with its paw

Tom believes that Jane likes pizza.


There is no pink dog.






Tom doesnt believe john like books



Homework
Convert the following statements into semantic network and conceptual
graph.
1. Mainframe and PC are computers
2. John threw the ball
3. Sarah fixed the chair with glue.
4. John gave Ahmed a book which is Zaki bought




Frame
A frame system represents an organization of knowledge about a set of
related concepts. All the information relevant to a concept is stored in a
single complex entity called a frame.

The frame consists of:
Objects: birds, fish.
Slots: properties such as color and size.
Slot-values: values stored in the slots, e.g. brown and large.
Slots and the corresponding slot-values are inherited through the class
hierarchy.

For Example
Birds and fish are animals. Birds are moving by fly and they lay
eggs. They have wings and their active at day light. kiwi and
alberto are birds. The color of kiwi is black and white and the color
of alberto is brown. Fish moves by swimming and has a skin.











brown
black and
white
alberto
color
color
kiwi
is-a
is-a
animals
eggs
lay
is-a
is-a
birds fish
move have
active
move has
day light
skin
Wings
swimming
fly

slot
value of slot













frame name: animals
live in: water
air
frame name: birds
a kind of: animals
move: fly
active at: day light
have part: wings
lay: eggs
frame name: fish
a kind of: animals
move: swimming
has part: skin
frame name: alberto
a kind of: birds
color: brown
frame name: K.W
a kind of: birds
color: black and white
subset
Member of
Member of
subset
Problem Solving
State space search
A state space is the set of all possible states of the problem under solving.

Problem Solving Operations
1. A set of states
2. Start state
3. Operator, possible moves, rules
4. Goal state
5. Determine the inference technique to inter the goal.

State Space Searches Examples:-
1) Monkey and Banana Problem
There is a monkey at the door in to a room. In the middle of the room a banana
is hugging from the ceiling. The monkey is hungry and wants to get the banana,
but he cannot stretch high enough from the floor. At the window of the room
there is a box the monkey may use.

The monkey can perform the following actions:-
Walk on the floor
Push the box a round (if it is already at the box).
Climb the box
Grasp the banana if standing on the box directly under the banana.

The question is Can the monkey get the banana?
The initial state of the problem is determined by:
1- Monkey is at door.
2- Monkey is on floor.
3- Box is at Window.
4- Monkey does not have banana.

Initial state: State (at door, on floor, at window, has not).
Goal state: State (at box, on box, under banana, has).

The arguments are:
At door and on floor: The positions of monkey.
At window: The position of box.
Has not: The monkey has not yet grasped the banana.

The actions are:
State1: It is the state before the move.
State2: It is the state after the move.
Move: It is the move that will be executed. Move (state1, state2, move).

To answer the question: Can the monkey get the banana?
This can be formulated as a predicate canget(state).The program canget can be
based on two observation:-
1) For any state in which the monkey already has the banana. The predicate
canget must certainly be true, no move is needed in this case:
canget(state(_,_,_,has)).
2) In other cases one or more moves are necessary.
canget(state1):-move(state1,state2,move),canget(state2).
The pseudo-code steps of monkey and banana problem is:
move (state (at door , on floor , at window , has not), state (at box , on floor , at
window , has not), walk).
move (state (at box , on floor , at window , has not) , state (at box, on floor, under
banana, has not), push).
move (state (at box, on floor, under banana, has not), state (at box, on box, under
banana, has not), climb).
move (state (at box, on box, under banana, has not), state (at box, on box, under
banana, has),grasp).

canget( state(_,_,_,has)).
canget (State1):- move (state1, state2,move), canget (state2).

goal: canget (state(at door, on floor, at window ,has not)).

The complete prolog program of monkey and banana problem:
domains
S=symbol.
state=st(S,S,S,S).

predicates
move(state,state,S).
canget(state).

clauses
move(st(atdoor,X,Y,Z),st(atbox,X,Y,Z),walk).
move(st(atbox,X,atwindow,Z),st(atbox,X,underbanana,Z),push).
move(st(atbox,onfloor,underbanana,Z),st(atbox,onbox,underbanana,Z),climb).
move(st(atbox,onbox,underbanana,hasnot),st(atbox,onbox,underbanana,has),gras
p).
canget(st(_,_,_,has)):-!.
canget(X):- move(X,Y,Action),!, write(X,",(",Action,"),",Y),nl, canget(Y).

/* goal: canget(st(atdoor,onfloor,atwindow,hasnot)).
st("atdoor","onfloor","atwindow","hasnot"),(walk),st("atbox","onfloor","atwindow
","hasnot")
st("atbox","onfloor","atwindow","hasnot"),(push),st("atbox","onfloor","underbana
na","hasnot")
st("atbox","onfloor","underbanana","hasnot"),(climb),st("atbox","onbox","underb
anana","hasnot")
st("atbox","onbox","underbanana","hasnot"),(grasp),st("atbox","onbox","underba
nana","has")
yes*/
2) A water Jug Problem
You are given two jugs, a 4-gallon one and a 3-gallon one. Neither has any
measuring marker on it. There is a pump that can be used to fill the jugs with
water. How can you get exactly 2 gallons of water into the 4-gallon jug?
The state space for this problem can be described as the set of ordered pairs of
integers (X,Y) , such that X=0,1,2,3, or 4 and Y=0,1,2, or 3; X represent the
number of gallons of a water in the 4-gallon jug , and Y represents the quantity of
water in 3-gallon jug. The start state is (0, 0). The goal state is (2, n) for any value
of n (since the problem does not specify how many gallons need to be in the 3-
gallon jug).

The state space search for the water Jug problem is:
(X,Y): order pair
X: water in 4-gallons X = 0,1,2,3,4
Y: water in 3-gallons Y = 0,1,2,3
start state: (0,0)
goal state: (2,n) where n = any value

The rules of the water Jug problem are:
1) (X,Y: X<4) (4,Y) Fill the 4 gallon jug
2) (X,Y: Y<3) (X,3) Fill the 3-gallon jug
3) (X,Y:X>0) (X-D,Y) Pour some water out of the 4-gallon jug
4) (X,Y: Y>0) (X,Y-D) Pour some water out of the 3-gallon jug
5) (X,Y: X>0) (0,Y) Empty the 4-gallon jug on the ground
6) (X,Y: Y>0) (X,0) Empty the 3-gallon jug on the ground
7) (X,Y: X+Y>=4 Y>0) (4,Y-(4-X)) Pour water from the 3-
gallon jug into the 4-
gallon jug until the 4-
gallon jug is full.

8) (X,Y: X+Y>=3 X>0) (X-(3-Y),3) Pour water from the 4-
gallon jug into the 3-
gallon jug until the 3-
gallon jug is full.
9) (X,Y: X+Y<=4 Y>0) (X+Y,0) pour all the
water from 3-
gallon jug into
the 4-gallon jug.
10) (X,Y: X+Y<=3 X>0) (0,X+Y) pour all the
water from 4-
gallon jug into the 3-
gallon jug.


The solution of the water jug problem is:

4-Gallon Jug 3-Gallon Jug Rule Applied
0 0
0 3 2
3 0 9
3 3 2
4 2 7
0 2 5
2 0 9









The solution can be shown as a search tree as follows:


























The prolog program to solve the water jug problem:

Domains
i=integer.
lst=st*.
st=jug(i,i).

predicates
path(st,st,lst)
move(st,st)
member(st,lst)
print(lst)

clauses
move(jug(2,Y),jug(2,Y)):-!.
move(jug(X,Y),jug(X,3)):-Y<3.
move(jug(X,Y),jug(4,Y)):-X<4.
move(jug(X,Y),jug(0,Y)):-X>0.
move(jug(X,Y),jug(X,0)):-Y>0.
move(jug(X,Y),jug(4,A)):-Z=X+Y,Z>=4,Y>0,A=Y-(4-X).
move(jug(X,Y),jug(B,3)):-Z=X+Y,Z>=3,X>0,B=X-(3-Y).
move(jug(X,Y),jug(Z,0)):-Z=X+Y,Z<=4,Y>0.
move(jug(X,Y),jug(0,Z)):-Z=X+Y,Z<=3,X>0.

path(G,G,L):- write("The solution path is:"),nl, print (L).
path(S,G,L):- move(S,S1),not(member(S1,L)),path(S1,G,[S1|L]).

print ([]).
print ([H|T]):- print(T),write(H),nl.

member(H,[H|_]):-!.
member(X,[_|T]):- member(X,T).

/*goal:
path(jug(0,0),jug(2,0),[]).
The solution path is:
jug(0,3)
jug(3,0)
jug(3,3)
jug(4,2)
jug(0,2)
jug(2,0)
yes*/



3) Tower of Hanoi Problem
The Tower of Hanoi is a mathematical puzzle. It consists of three rods, and a
number of disks of different sizes which can slide onto any rod. The puzzle starts
with the disks in a neat stack in ascending order of size on one rod, the smallest at
the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
1- Only one disk can be moved at a time.
2- Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
3- No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number
of moves required to solve a Tower of Hanoi puzzle is 2n+1, where n is the
number of disks.
The below figure shows the trace to solve the Tower of Hanoi problem:




The prolog program of Tower of Hanoi problem:
domains
loc=symbol

predicates
hanoi(integer)
move(integer,loc,loc,loc)
print(loc,loc)
clauses
hanoi(N) :- move(N, left, middle, right).
move(0, _, _, _) :- !.
move(N, X, Y, Z) :-
M = N-1,
move(M, X, Z, Y),
print(X, Y),
move(M, Z, Y, X).
print(Loc1,Loc2):-
write("\n move disc from ",Loc1," to " ,Loc2).

goal:
hanoi(3).
/* move disc from left to middle
move disc from left to right
move disc from middle to right
move disc from left to middle
move disc from right to left
move disc from right to middle
move disc from left to middle
yes
*/

Vous aimerez peut-être aussi