CS 381: Programming Language...

51
CS 381: Programming Language Fundamentals Summer 2017 Introduction to Logic Programming in Prolog Aug 2, 2017

Transcript of CS 381: Programming Language...

CS381:ProgrammingLanguageFundamentals

Summer2017

IntroductiontoLogicProgramminginPrologAug2,2017

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation2

Programmingparadigms

Programmingparadigms3

Whatisaprogrammingparadigm?

Paradigm:Aconceptualmodelunderlyingthetheoriesandpracticeofascientificsubject

Programmingparadigms4

scientificsubject=programming

Programmingparadigm:Aconceptualmodelunderlyingthetheoriesandpracticeofprogramming

Imperativeparadigm

Needstwosub-languages:• expressionstodescribevaluestostoreinvariables(Expr)• statementstodescribestatechangesandcontrolflow(Stmt)

Semanticfunctions:• semE :: Expr -> State -> Val • semS :: Stmt -> State -> State

Programmingparadigms5

Imperativemodeldatasetofstatevariablestype State = [(Name,Val)] computationtransformationofstateState -> State

Object-orientedparadigm

Needsexpressionandstatementsub-languages,butalsoextendedstatementswith:• constructstocreateobjectsandinvokemethods

Newstatementsemanticfunction:• semS :: Stmt -> [Object] -> [Object]

Programmingparadigms6

Object-orientedmodeldatasetofobjectswithstatetype Object = (State,[Method]) type Method = (Name, State -> State) computationevolutionofobjects[Object] -> [Object]

Anextension/refinementoftheimperativeparadigm

Functionalparadigm

Generallyjustonelanguage(e.g.lambdacalculus):• expressionsdescribefunctionsandvalues(Expr)

Semanticfunctions:• sem :: Expr -> Val

Programmingparadigms7

Functionalmodeldatastructuredvaluesdata Val = ... computationfunctionsovervaluesVal -> Val

Logicparadigm

Generallyjustonelanguage:• relationsdescribebothknowledgeandqueries(Rel)

Semanticfunctions:• sem :: Rel -> Query

Programmingparadigms8

Logicalmodeldatasetofvaluesandrelationstype Known = [(Val,...,Val)] computationqueryoverrelationstype Query = Known -> Known

ParadigmViewofcomputation

Comparisonofprogrammingparadigms

Programmingparadigms9

imperativeobject-orientedfunctionallogic

sequenceofstatetransformationssimulationofinteractingobjectsfunctionmappinginputtooutputqueriesoverlogicalrelations

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation10

WhatisProlog?

• anuntypedlogicprogramminglanguage

• programsarerulesthatdefinerelationsonvalues

• runaprogrambyformulatingagoalorquery• resultofaprogram:atrue/falseanswerandabindingoffreevariables

Logicprogrammingbasics11

Logic:atoolforreasoning

Syllogism(logicalargument)—Aristotle,350BCE

Everyhumanismortal.

Socratesishuman.Therefore,Socratesismortal.

First-orderlogic—GottlobFrege,1879Begriffsschrift

Logicprogrammingbasics12

�x.Human(x) � Mortal(x)Human(Socrates)� Mortal(Socrates)

Logicandprogramming

Logicprogrammingbasics13

rule �x.Human(x) � Mortal(x)fact Human(Socrates)

goal/query � Mortal(Socrates)

logicprogram

logicprogramexecution

Prologprogrammortal(X) :- human(X). human(Socrates).

Prologquery(interactive)?- mortal(Socrates). true.

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation14

PredicateDescription

SWI-Prologlogistics

Logicprogrammingbasics15

[myfile]. listing(P). trace. nodebug. help. halt.

loaddefinitionsfrom“myfile.pl”listsfactsandrulesrelatedtopredicatePturnontracingturnofftracingopenhelpwindow(requiresX11onMac)quit

GNU-Prologusesthesamecommands—excepthelp!

Atoms

Anatomisjustaprimitivevalue

• stringofcharacters,numbers,underscoresstartingwithalowercaseletter:

• hello,socrates,uP_aNd_4tOm

• anysinglequotedstringofcharacters:

• ‘Hello world!’,‘Socrates’

• numericliterals:123,-345

• emptylists:[]

Logicprogrammingbasics16

Variables

Avariablecanbeusedinrulesandqueries

• stringofcharacters,numbers,underscoresstartingwithanuppercaseletteroranunderscore• X,SomeHuman,_g_123, This_Human

• specialvariable:_(justanunderscore)

• unifieswithanything—“don’tcare”

Logicprogrammingbasics17

Predicates

BasicentityinPrologisapredicate

Logicprogrammingbasics18

�= relation �= set

Unarypredicatehobbit(bilbo). hobbit(frodo). hobbit(sam).

Binarypredicatelikes(bilbo, frodo). likes(frodo, bilbo). likes(sam, frodo). likes(frodo, ring).

hobbit = {bilbo, frodo, sam}

likes = {(bilbo, frodo), (frodo, bilbo) (sam, frodo), (frodo, ring)}

Simplegoalsandqueries

Predicatesare:

• definedinafile• queriedintheREPL

Responsetoaqueryisatrue/falseanswer

whentrue,providesabindingforeachvariableinthequery

Logicprogrammingbasics19

theprogramrunningtheprogram

Issamahobbit??- hobbit(sam). true.

Isgimliahobbit??- hobbit(gimli). false.

(oryes/no)

Whoisahobbit??- hobbit(X). X = bilbo ; X = frodo ; X = sam .

Type;aftereachresponsetosearchforanother

Queryingrelations

Youcanqueryanyargumentofapredicate

• thisisfundamentallydifferentfrompassingargumentstofunctions!

June13,201520

Definitionlikes(bilbo, frodo). likes(frodo, bilbo). likes(sam, frodo). likes(frodo, ring).

?- likes(frodo, Y). Y = bilbo ; Y = ring .

?- likes(X, frodo). X = bilbo ; X = sam .

?- likes(X, Y). X = bilbo, Y = frodo ; X = frodo, Y = bilbo ; X = sam, Y = frodo ; X = frodo, Y = ring .

hobbits.pl

Overloadingpredicates

Predicateswiththesamenamebutdifferentaritiesaredifferentpredicates!

Logicprogrammingbasics21

hobbit/1 hobbit(bilbo). hobbit(frodo). hobbit(sam).

hobbit/2 hobbit(bilbo, rivendell). hobbit(frodo, hobbiton). hobbit(sam, hobbiton). hobbit(merry, buckland). hobbit(pippin, tookland).

?- hobbit(X). X = bilbo ; X = frodo ; X = sam .

?- hobbit(X,_). ... X = merry ; X = pippin .

hobbits.pl

Conjunction

Comma(,)denoteslogicalandoftwopredicates

Logicprogrammingbasics22

likes(frodo, sam). likes(sam, frodo). likes(frodo, ring).

hobbit(frodo, hobbiton). hobbit(sam, hobbiton). hobbit(merry, buckland). hobbit(pippin, tookland).

Dosamandfrodolikeeachother??- likes(sam,frodo), likes(frodo,sam). true.

Domerryandpippinliveinthesameplace??- hobbit(merry,X), hobbit(pippin,X). false.

Doanyhobbitsliveinthesameplace??- hobbit(H1,X), hobbit(H2,X), H1 \= H2. H1 = frodo, X = hobbiton, H2 = sam.

H1andH2mustbedifferent!

Rules

Notethatdisjunctionisdescribedbymultiplerules

Logicprogrammingbasics23

Rule:head :- bodyTheheadistrueifthebodyistrue

Exampleslikes(X,beer) :- hobbit(X,_). likes(X,boats) :- hobbit(X,buckland).

danger(X) :- likes(X,ring). danger(X) :- likes(X,boats), likes(X,beer).

hobbits.pl

Prolog

24Logicprogrammingbasics

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation25

HowdoesPrologsolvequeries?

Understandingthequeryengine26

Basicalgorithmforsolvinga(sub)goal1. linearlysearchdatabaseforcandidatefacts/rules2. attempttounifycandidatewithgoal

ifunificationissuccessful:• ifafact—we’redonewiththisgoal!• ifarule—addbodyofruleasnewsubgoal

ifunificationisunsuccessful:keepsearching3. backtrackifwereachtheendofthedatabase

1.linearlysearchthedatabaseforcandidatefacts/rules

Whatisacandidatefact/rule?

• fact:predicatematchesthegoal

• rule:predicateofitsheadmatchesthegoal

Understandingthequeryengine27

Examplegoal:likes(merry,Y)

Candidateslikes(sam,frodo). likes(merry,pippin). likes(X,beer) :- hobbit(X).

Notcandidateshobbit(merry,buckland). danger(X) :- likes(X,ring). likes(merry,pippin,mushrooms).

2.attempttounifycandidatewithgoal

Understandingthequeryengine28

UnificationFindanassignmentofvariablesthatmakesitsargumentssyntacticallyequalProlog:A = BmeansattempttounifyAandB

Candidates?- likes(merry,Y) = likes(sam,frodo). false.

?- likes(merry,Y) = likes(merry,pippin). Y = pippin .

?- likes(merry,Y) = likes(X,beer). X = merry ; Y = beer .

2a.iffail,trynextcandidate

2b.ifsuccess,addnewsubgoal(s)

Trackingsubgoals

Understandingthequeryengine29

Derivingsolutionsthroughrules1. maintainalistofgoalsthatneedtobesolved• whenthislistisemptywe’refinished!

2. ifcurrentgoalunifieswitharulehead,addbodyassubgoalstolist3. afterunification,substitutevariablesinallgoalsinthelist!

Databaselt(one,two). lt(two,three). lt(three,four). lt(X,Z) :- lt(X,Y), lt(Y,Z).

Sequenceofgoalsforlt(one,four) lt(one,four) 4: X=one,Z=four lt(one,Y1), lt(Y1,four) 1: Y1=two lt(two,four) 4: X=two,Z=four lt(two,Y2), lt(Y2,four) 2: Y2=three lt(three,four) 3: true done!

1 2 3 4

3.Backtracking

Foreachsubgoal,Prologmaintains:

• thesearchstate(goals+assignments)beforeitwasproduced

• apointertotherulethatproducedit

Whenasubgoalfails:

• restorethepreviousstate

• resumesearchforpreviousgoalfromthepointer

Whentheinitialgoalfails:returnfalse

Understandingthequeryengine30

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation31

Potentialforinfinitesearch

Whycareabouthowgoalsearcheswork?

Onereason:sowecanwriterecursiverulesthatdon’tloopforever!

Understandingthequeryengine32

Contra-example:symmetrylikes(frodo,sam). likes(merry,pippin). likes(frodo,bilbo). likes(X,Y) :- likes(Y,X).

?- likes(bilbo,merry). ERROR: Out of local stack

Contra-example:transitivitylt(one,two). lt(two,three). lt(three,four). lt(X,Z) :- lt(X,Y), lt(Y,Z).

?- lt(three,one). ERROR: Out of local stack

hobbits.pl

Strategiesforwritingrecursiverules

Understandingthequeryengine33

Howtoavoidinfinitesearch1. alwayslistnon-recursivecasesfirst2. use“helper”predicatestoenforceprogressduringsearch

Example:symmetrylikesP(frodo,sam). likesP(merry,pippin). likesP(frodo,bilbo). likes(X,Y) :- likesP(X,Y). likes(X,Y) :- likesP(Y,X).

?- likes(bilbo,merry). false.

Example:transitivityltP(one,two). ltP(two,three). ltP(three,four). lt(X,Y) :- ltP(X,Y) lt(X,Z) :- ltP(X,Y), lt(Y,Z).

?- lt(three,one). false.

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation34

Representingstructureddata

Canrepresentstructureddatabynestedpredicates

Complextermsandlists35

Exampledatabaserides(gandalf, horse(white)). rides(sam, donkey(grey)). rides(frodo, pony(grey)). rides(strider, horse(black)).

?- rides(gandalf, X). X = horse(white) .

?- rides(X, horse(Y)). X = gandalf, Y = white ; X = strider, Y = black .

Variablescannotbeusedforpredicates:?- rides(X, Y(grey)). � illegal!

hobbits.pl

RelationshiptoHaskelldatatypes

Complextermsandlists36

Haskelldatatypedata Exp = Lit Int | Neg Exp | Add Exp Exp | Mul Exp Exp

Add (Neg (Lit 3)) (Mul (Lit 4) (Lit 5))

Prologpredicateexp(N) :- number(N). exp (neg(E)) :- exp(E). exp (add(L,R)) :- exp(L), exp(R). exp (mul(L,R)) :- exp(L), exp(R).

add(neg(3),mul(4,5))

• buildvaluesw/dataconstructors

• datatypesstaticallydefinevalidcombinations

• buildvaluesw/predicates

• userulestodynamicallyidentifyorenumeratevalidcombinators

exp.plbool.pl

Equality

Complextermsandlists37

Differentformsofequalitybetweenterms1. unification2. equivalence3. evaluation

`=` and`\=` `==` and `\==` `=:=` and `=\=`

Unificationequality

Twotermsareequalwhentheycanbeinstantiatedsothattheybecomeidentical

38Complextermsandlists

?- 3=3. true.

?- X=3. X = 3.

?- X=Y. X = Y.

?- likes(X,red)=likes(john,Y). X = john, Y = red.

?- car(red)=car(X). X = red.

?- 3=4. false.

?- 3+1=4. false.

term

evaluationequality

Unification

AunifierfortwotermsTandT’isasubstitutionforvariablesσ,suchthat:σ(T) = σ(T’)

39Complextermsandlists

?- 3=3. true.

?- X=3. X = 3.

?- X=Y. X = Y.

?- likes(X,red)=likes(john,Y). X = john, Y = red.

?- car(red)=car(X). X = red.

σ = {} σ(3) = 3 = σ(3)

σ = {X -> 3} σ(X) = 3 = σ(3)

σ = {X -> Y} σ(X) = Y = σ(Y)

σ = {X -> john, Y -> red} σ(likes(X,red)) = likes(john,red) = σ(likes(john,Y))

σ = {X -> red} σ(car(red)) = σ(car(X))

Equivalence

Twotermsareequivalentiftheyareidentical.

40Complextermsandlists

?- 3==3. true.

?- X=3, X==3. X = 3.

?- X=Y, X==Y. X = Y.

?- X==3. false.

?- X==Y. false.

differentfromobject/referenceequality

?- X==Y, X=Y. false.

Evaluationequality

Twotermsareevaluationequivalentiftheyevaluatetothesamenumber.

41Complextermsandlists

?- 3+1=:=4. true.

?- X=3, X*2=:=X+3. X = 3.

?- 3+1==4. false.

?- 3+1=4. false.

?- 3=:=X. ERROR: =:=/2: Arguments are not sufficiently instantiated

?- X*2=:=X+3, X=3. ERROR: =:=/2: Arguments are not sufficiently instantiated

Listconstruction

Listsaretermswithspecialsyntax

Complextermsandlists42

3

4

5 []

3

4 5 6 []

Cons Functor Empty List

HaskellProlog

Listpatterns

Complextermsandlists43

story([3,little,pigs])

?- story([X|Y]).

X = 3, Y = [little,pigs].

Head Tail

?- story([X,Y|Z]).

X = 3, Y = little, Z = pigs.

?- story([X,Y,Z]).

X = 3, Y = little, Z = pigs.

?- story([X,Y,Z|V]).

X = 3, Y = little, Z = pigs, V = [].

?- story([X,Y,Z,V]).

false.

x:y:z [X,Y|Z]

[x,y,z] [X,Y,Z]

Listpredicates

Complextermsandlists44

member(X,[X|_]). member(X,[_|Y]) :- member(X,Y). wildcard—matchesanything

?- member(3,[2,3,4,3]). true ; true.

?- member(3,[2,3,4,3,1]). true ; true ; false.

?-member(2,[2,3,4,3]). true ; false.

?-member(X,[3,4]). X = 3 ; X = 4.

?-member(3,L). L = [3|A] ; L = [A,3|B] ; L = [A,B,3|C] …

ArithmeticinProlog

Complextermsandlists45

Arithmeticexpressionsarealsoconstructeddata(nestedpredicates)• specialsyntax:canbewritteninfix,standardoperatorprecedence• canbeevaluated:

XisexpevaluateexpandbindtoXexp=:=expevaluateexpressionsandcheckifequal

Arithmeticoperations+-*/mod

3*4+5*6 ≡ +(*(3,4), *(5,6))

Comparisonoperations<>=<>==:==\=

?- X is 3*4+5*6. X = 42.

?- 8 is X*2. ERROR: is/2: Arguments are not sufficiently instantiated

Usingarithmeticinrules

Complextermsandlists46

?- fac(5,M). X = 120.

?-fac(N,6). ERROR: fac/2: Arguments are not sufficiently instantiated

Exampledatabasefac(1,1). fac(N,M) :- K is N - 1, fac(K,L), M is L*N.

Unificationvs.arithmeticequality

Complextermsandlists47

?- X = 3*5. X = 3*5.

Unification:A = BFindanassignmentofvariablesthatmakesitsargumentssyntacticallyequal

Arithmeticequality:A =:= BEvaluatetermsasarithmeticexpressionsandcheckifnumericallyequal

?- 8 = X*2. false.

?- 4*2 = X*2. X = 4.

?- X is 3*5. X = 15.

?- 8 is X*2. ERROR: is/2: Arguments are not sufficiently instantiated.

Outline

Programmingparadigms

LogicprogrammingbasicsIntroductiontoPrologPredicates,queriesandrules

UnderstandingthequeryengineGoalsearchandunificationStructuringrecursiverules

Complextermsandlists

Cutsandnegation48

Howcutworks

Cutsandnegation49

Cutisaspecialatom! usedtopreventbacktrackingWhenencounteredasasubgoalit:

• alwayssucceeds• commitsthecurrentgoalsearchtothematchesandassignmentsmadesofar

Databasewithoutcutfoo(1). foo(2). bar(X,Y) :- foo(X), foo(Y). bar(3,3).

?- bar(A,B). A = 1, B = 1 ; A = 1, B = 2 ; A = 2, B = 1 ; A = 2, B = 2 ; A = 3, B = 3 .

Databasewithcutfoo(1). foo(2) bar(X,Y) :- foo(X), !, foo(Y). bar(3,3).

?- bar(A,B). A = 1, B = 1 ; A = 1, B = 2.

Greencutsvs.redcuts

Cutsandnegation50

Agreencut:doesn’taffectthemembersofapredicate

• onlycutspathsthatwouldhavefailedanyway

• thecutisusedpurelyforefficiency

Aredcut:anycutthatisn’tgreen

• ifremoved,meaningofthepredicatechanges

• thiscutispartofthe“logic”ofthepredicate

max(X,Y,Y) :- X < Y, !. max(X,Y,X) :- X >= Y.

find(X,[X|_]) :- !. find(X,[_|L]) :- find(X,L).

Negationasfailure

Cutsandnegation51

Negationpredicatenot(P) :- P, !, fail. not(P).

?- not(likes(frodo,beer)). false.

?- not(likes(gimli,beer)). true.

?- not(likes(bilbo,X)). false.

?- not(likes(X,pizza)). true.

Exampledatabasehobbit(frodo). hobbit(bilbo). likes(X,beer) :- hobbit(X).