Prolog,Prolog Programming IN AI.pdf

Rabiabashir21 695 views 21 slides Jul 07, 2022
Slide 1
Slide 1 of 21
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21

About This Presentation

Prolog, Prolog Programming IN AI. Prolog is an Artificial Intelligence programming language. Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Its applications include natural language understanding and expert systems. Prolog is notably a s...


Slide Content

Prolog Programming

Introduction
Prolog
Prologisalogicprogramminglanguage.It
hasimportantroleinartificialintelligence.
Unlikemanyotherprogramminglanguages,
Prologisintendedprimarilyasadeclarative
programminglanguage.Inprolog,logicis
expressedasrelations(calledasFactsand
Rules).Coreheartofprologliesat
thelogicbeingapplied.Formulationor
Computationiscarriedoutbyrunninga
queryovertheserelations.
4
Prolog

Prologprogramissimplybasedonpredicate
logicknownasHornclause.Inprolog,we
composetheprogramusingfactsandrulesand
weposeaqueryonquerypromptaboutthe
factsandrulesweinserted.
5Prolog Programming Basics
HornClause:Hornclauseconsistsofhead(lefthand
side)andbody(righthandside).Headcanhave0or1
predicateandbodycanhavelistofpredicates.That
meansLHShasonlysingleliteralandRHScanhave
morethanoneliterals.
head:-body.

What is Prolog?
»PrologorPROgramminginLOGicsisalogicaland
declarativeprogramminglanguage.Itisonemajorexample
ofthefifthgenerationlanguagethatsupportsthe
declarativeprogrammingparadigm.Thisisparticularly
suitableforprogramsthatinvolvesymbolicornon-
numericcomputation.Thisisthemainreasontouse
PrologastheprogramminglanguageinArtificial
Intelligence,wheresymbolmanipulationandinference
manipulationarethefundamentaltasks.
»InProlog,weneednotmentionthewayhowoneproblem
canbesolved,wejustneedtomentionwhattheproblem
is,sothatPrologautomaticallysolvesit.However,inProlog
wearesupposedtogivecluesasthesolutionmethod.
6

Programminglanguagesareoftwokinds:
Procedural(BASIC,Fortran,C++,Pascal,
Java);
Declarative(LISP,Prolog,ML).
Inproceduralprogramming,wetellthe
computerhowtosolveaproblem.
Indeclarativeprogramming,wetellthe
computerwhatproblemwewantsolved.
SWI-PrologoffersacomprehensivefreeProlog
environment.Sinceitsstartin1987,SWI-Prolog
developmenthasbeendrivenbytheneedsofreal
worldapplications.SWI-Prologiswidelyusedin
researchandeducationaswellascommercial
applications.
PrologwasoriginallydesignedtobeanAIlanguage,
anditisverywellsuitedforexpertsystems,planning
systemsandsimilarAIapplications.
Logic Programming: Prolog
SWI -Prolog
ThelogicprogramminglanguagePROLOG(ProgrammationenLogique)
wasconceivedbyAlainColmerauerattheUniversityofAix-Marseille,
France,wherethelanguagewasfirstimplementedin1973.PROLOGwas
furtherdevelopedbythelogicianRobertKowalski,amemberoftheAIgroup
attheUniversityofEdinburgh.

8
Machine
Logical Programming
Machine
Answer
Int main()
{
Procedure 1 ()
Procedure 2 ()
return
}
Knowledge
Base
Queries
Functional Programming
Prolog Interpreter
Facts & Rules

Rulesareextinctionsoffacts
thatcontainconditional
clauses.Tosatisfyarule
theseconditionsshouldbe
met.
Rules
Andtorunaprolog
program,weneedsome
questions,andthose
questionscanbeanswered
bythegivenfactsandrules
Questions
Factsarestatements
thatdescribeobject
propertiesorrelations
betweenobjects.
Thefactispredicatethat
istrue,forexample,ifwe
say,“Tomisthesonof
Jack”,thenthisisafact.
Facts
Prolog language basically has three different elements −
Facts Rules Queries

Prolog Syntax
The syntax of Prolog is as follows:
relationship(object1,object2)

Prolog
»Example:
»“Arslan owns the book”
»Owns (arslan, book) relationship(object1, object2)
»The relationship has a specific order, arslan own the
book, but the book dose not owns arslan, and this
relationship and its representation above called fact.
11

English Predicate CalculusProlog
If → :-
Not ~ Not
Or V ;
and ^ ,
female,Male,X,Y,mother_of,_father,Pro34
Variableisastring.Thestringcanbeacombinationoflowercaseor
uppercaseletters.Thestringcanalsocontainunderscorecharacters
thatbeginwithanunderscoreoranupper-caseletter.Rulesfor
formingnamesandpredicatecalculusarethesame.
Usingthefollowingtruth-functionalsymbols,theProlog
expressionsarecomprised.Thesesymbolshavethesame
interpretationasinthepredicatecalculus.
Symbols
Variables

13
Afactislikeapredicateexpression.Itisusedtoprovideadeclarativestatementaboutthe
problem.InaPrologexpression,whenavariableoccurs,itisassumedtobeuniversally
quantified.Factsarespecifiedintheformofthehead.Headisknownastheclausehead.Itwill
takeinthesamewayasthegoalenteredatthepromptbytheuser.
Facts
cat(momo). /*momoisacat*/
dog(pulu). /*puluisadog*/
likes(arslan, jolie). /*ArslanlikesJolie*/
not(likes(Jolie,pasta)). /*Joliedoesnotlikepasta*/
Forexample:
Queries
InProlog,thequeryistheactionofaskingtheprogramabouttheinformationwhichisavailable
withinitsdatabase.WhenaPrologprogramisloaded,wewillgetthequeryprompt,
?-'Itissunny'.
yes
?-
?-'Itiscold'.
no
?-
no
?-
?-’momoiscat'.
yes
?-
?-’momoisdog'.

Rules extend the logic program capabilities. Rules are used
to provide the decision-making process in Prolog. Rules are
specified in the form:
head:-t1,t2,t3,…..,tk.Wherek>=1
The head is known as the clause of the head.
:-isknownastheclauseneck.It
isreadas'if'.Thebodyofthe
clauseisspecifiedbyt1,t2,t3,…,
tk.Itcontainsoneormore
components,anditcanbe
separatedusingthecommas.A
rulewillreadas'headistrueif
t1,t2,t3,….,tkarealltrue'.
Rules
In the following program, first two lines indicate the facts and last two lines indicate the rules:
dog(pulu).large(pulu).
cat(momo).large(momo).
large_animal(A):-dog(A),large(A).
large_animal(C):-cat(C),large(C).
Theaboverulesmeanthat'large_animal(A)istrueifdog(A)istrue,andlarge(A)istrue,etc.'
Thelastlinemeansthat'large_animal(C)istrueifcat(C)istrue,andlarge(C)istrue.
Facts and Rules make up
the knowledge base.

likes(tarzan, jane).
likes(jane, tarzan).
likes(terk, jane).
facts
Arguments / objects / items
.dot is necessary to end the statement
relation
friends(X,Y):-likes(X,Y), likes(Y,X).
Predicate name
head body
variables
Horn Clause

Example
elephant(george).
elephant(mary).
elephant(X) :-grey(X), mammal(X), hasTrunk(X).
Procedure for elephant
Predicate
Clauses
Rule
Facts
?-elephant(george).
yes
?-elephant(jane).
no
Queries
Replies

Queries
Rules
facts
Example 1 :Belowfoodtable shows the facts, rules, goals and their English meanings.
Queries / Goals
?-food(pizza). // Is pizza a food?
?-meal(X), lunch(X). // Which food is meal and lunch?
?-dinner(sandwich). // Is sandwich a dinner?
Facts English meanings
food(burger). // burger is a food
food(sandwich). // sandwich is a food
food(pizza). // pizza is a food
lunch(sandwich). // sandwich is a lunch
dinner(pizza). // pizza is a dinner
Rule
meal(X) :-food(X).
// Every food is a meal OR
Anything is a meal if it is a food

Queries
Rules
facts
Example 2 :Below student-professor relation table shows the facts, rules, goals and their English meanings.
.
Facts English meanings
studies(charlie, csc135). // charlie studies csc135
studies(olivia, csc135). // oliviastudies csc135
studies(jack, csc131). // jack studies csc131
studies(arthur, csc134).
likes('John', car(bmw))
// arthur studies csc134
// Read as : john likes bmwcar
gives(john, chocolate, jane). // Read as : john gives chocolate to jane
Rules
professor(X, Y) :-
teaches(X, C),studies(Y, C).
// X is a professor of Y if X teaches
C and Y studies C.
Queries / Goals
?-studies(charlie, What).
// charlie studies what? OR
What does charlie study?
?-professor(kirke, Students).
// Who are the students of
professor kirke.

19
ListsandSequenceinProlog
InProlog,thelistbuilderusesbrackets[...].Alistisreferredbythe
notation[A|B]inwhich,Aisthefirstelement,andwhosetailisB.
Thefollowingexampleshowsthethreedefinitions,wherethefirst
elementofthelistisrefereedbythe'car',thetailofthelistisreferred
by'cdr',listconstructorisreferredbythe'cons'.
car([A|B],A).
cdr([A|B],B).
cons[A,B,[A|S]).
Where,
•Aisthehead(car)of[A|B].
•Bisthetail(car)of[A|B].
•PutAattheheadandBasthetailconstructsthelist[A|S].
Thepredicate'member/2'definitionisdescribedasfollows:
member(A,[A|S]).
member(A,[B|S]):-member(A,S).
Theclausescanbereadasfollows:
•AisalistmemberwhosefirstelementisA.
•AisalistmemberwhosetailisSifAisamemberofS.

Theloopingfacilityiscontainedinmostoftheprogramming
languages.Loopingisusedtoenableasetofinstructionsto
berepeatedlyexecutedeitherafixednumberoftimesor
untilagivenconditionmet.Prologhasnoloopingfacility,
butwecanobtainasimilareffect.Usingthiseffect,wecan
evaluateasequenceofgoalsrepeatedly.Invariousways,
thiscanbedonelikebuilt-inpredicates,recursion,
backtracking,oracombinationofthese.
Intheaboveexample,wedefinethelooppredicatein
termsofitself.Thesecondclausereadas'toloopfromN,
firstwritetheN'svalue,thensubtractonetoprovideS,
thenloopfromM'.Thisprocesswillterminateusing
thefirstclause:'whentheargumentis0,thenstopordo
nothing'.Herethefirstclauseiscalledasterminated
condition.
Loopingafixednumberoftimes
Toexecutetheinstructionafixednumberoftimes,many
programminglanguagesprovide'forloop'.InProlog,there
isnosuchfacilityavailabledirectly,butusingrecursion,we
canobtainasimilareffect,whichisshowninthefollowing
programs:
LoopsinProlog
Example1:
Thisprogramoutputstheintegervaluefromaspecified
valuedownto1.
loop(0).
loop(N):-N>0,write('valueofNis:'),write(N),nl.
SisN-1,loop(S).
?-loop(4).
valueofNis:4
valueofNis:3
valueofNis:2
valueofNis:1
yes

Here are some simple clauses.
The following queries yield the specified answers.
How do you add the following facts?
likes(mary,food).
likes(mary,juice).
likes(john,juice).
likes(john,mary).
| ?-likes(mary,food).
yes.
| ?-likes(john,juice).
yes.
| ?-likes(john,food).
no.
John likes anything that Mary likes
John likes anyone who likes juice
John likes anyone who likes themselves
Example 3 :

Some Applications of Prolog
Prologisusedinvarious
domains.Itplaysavitalrolein
automationsystem.Following
aresomeotherimportant
fieldswherePrologisused−
Prologisusedinvarious
domains.Itplaysavitalrolein
automationsystem.Following
aresomeotherimportant
fieldswherePrologisused−
•IntelligentDatabaseRetrieval
•NaturalLanguageUnderstanding
•SpecificationLanguage
•MachineLearning
•RobotPlanning
•AutomationSystem
•Problem Solving
•Expert Systems
What is
Prolog used
for
Good at
▪Grammars and Language processing,
▪Knowledge representation and reasoning,
▪Unification,
▪Pattern matching,
▪Planning and Search.
i.e. Prolog is good at Symbolic AI.
?

23
Advantages :
1.Easy to build database. Doesn’t
need a lot of programming effort
2.Pattern matching is easy.
Search is recursion based
.3.Ithasbuiltinlisthandling.
Makesiteasiertoplaywith
anyalgorithminvolvinglists.
2.Sometimes input and output is
not easy.
Disadvantages :
1.LISP(anotherlogic
programming language)
dominatesoverprologwith
respecttoI/Ofeatures
3. Repetitive number crunching,
Representing complex data
structures,
Input/output (interfaces).