02 - syntax and semantics - uni-bonn.de · prolog syntax and semantics syntax model-theoretic...

124
„Advanced Logic Programming“ Summer semester 2009 R O O T S Chapter 2 Chapter 2. Prolog Syntax and Semantics Syntax Model-theoretic semantics (“Logical Consequence”) Operational semantics (Derivation / Resolution) Operational semantics ( Derivation / Resolution ) Negation as failure Disjunction - June 7, 2009 -

Upload: others

Post on 27-Oct-2019

65 views

Category:

Documents


0 download

TRANSCRIPT

„Advanced Logic Programming“Summer semester 2009 R O O T SSu e se es e 009

Chapter 2 Chapter 2. Prolog Syntax and Semantics

SyntaxModel-theoretic semantics (“Logical Consequence”)

Operational semantics (“Derivation / Resolution”)Operational semantics ( Derivation / Resolution )Negation as failure

Disjunction

- June 7, 2009 -

This chapter is partly based on slides from the course “Deskriptive Programmierung” held in the summer semester 2008 by Prof. Dr. Rainer Manthey and Dr. Andreas Behrend.

I want to thank the authors for the permission to use and adapt their material for this course.

-- Günter Kniesel, April 2009

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-2 R O O T S

Prolog

Prolog stands for "Programming in Logic".It i th t l i lIt is the most common logic program language.

Bits of historyBits of history1965

John Alan Robinson develops the resolution calculus – the formal pfoundation of automated theorem provers

1972Alain Colmerauer (Marseilles) develops Prolog (first interpreter)Alain Colmerauer (Marseilles) develops Prolog (first interpreter)

mid 70thDavid D.H. Warren (Edinburg) develops first compiler( g)

Warren Abstract Machine (WAM) as compilation target like Java byte code

1981-925th G ti P j t“ i J b t d ti f P l ld id

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-3 R O O T S

„5th Generation Project“ in Japan boosts adoption of Prolog world-wide

Chapter 2: Syntax and Semantics

Prolog Syntax

PredicatesClauses, Rules, Facts, ,

Terms, Variables, Constants, StructuresPunctuation symbols and Operators

R O O T S

Predicates, Clauses, Rules, Facts

Predicate symbol (just a name) Predicate definition (set of clauses)

isFatherOf(kurt,peter). isFatherOf(peter,paul).isFatherOf(peter hans)

FactisFatherOf(peter,hans).

isGrandfatherOf(G,C) :-isFatherOf(G,F), isFatherOf(F,C).

Implication

isGrandfatherOf(G,C) :-isFatherOf(G,M), isMotherOf(M,C).

Rule

Lit l

Clause

C

?- isGrandfatherOf(kurt,paul).? isGrandfatherOf(kurt C)

Literal Conjunction

?- isGrandfatherOf(kurt,C).?- isGrandfatherOf(G,paul).?- isGrandfatherOf(G,paul),isFatherOf(X,G).

Goal / Query

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-5 R O O T S

Clauses and Literals

Prolog programs consist of clausesR l f t i ( i lid )Rules, facts, queries (see previous slide)

Clauses consist of literals separated by logical connectors.p y gLogical connectors are

implication (:-), conjunction (,) and disjunction (;)

isGrandfatherOf(G,C) :-isFatherOf(G,X), ( isFatherOf(X,C) ; isMotherOf(X,C) ).

Literals consist of a predicate symbol, punctuation symbols and arguments

Punctuation symbols are the comma “,” and the round braces “(“ and “)”

isGrandfatherOf(G,C)isFatherOf(peter hans)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-6 R O O T S

isFatherOf(peter,hans)fieldHasType(FieldName, type(basic,TypeName,5) )

Rules

Rules consist of a head and a body.

“head literal”represents the predicate that is defined by the clause

isGrandfatherOf(G,C) :-isFatherOf(G,X), ( isFatherOf(X,C) ; isMotherOf(X,C) ).

“body literals”represent goals to be proven in order to

prove the head.

Facts are just syntactic sugar for rules with the body “true”.

isFatherOf(peter hans) :- true

isFatherOf(peter,hans).these clauses are equivalent

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-7 R O O T S

isFatherOf(peter,hans) : true.

Terms

Terms are the arguments of literals. They may beV i bl h h dVariables X,Y, Father, Method, Type, _type, _Type, . . .Constants Numbers, Strings, ...Function terms person(stan,laurel), +(1,*(3,4)), …p ( , ), ( , ( , )),

Terms are the only data structure in Prolog!Terms are the only data structure in Prolog!

The only thing one can do with terms is unification with other terms!

Prolog can interpret terms as programs!g p p gA Prolog program can easily interpret or modify itself or other programsWe shall discuss this in the chapter about “Metaprogramming”.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-8 R O O T S

Variables: Syntax

Variables start with an upper case letter or an underscore '_'.

Country Year M V _45 _G107 _europe _

i t l i hinternal naming schemefor variables

Anonymous Variables ('_')For irrelevant values“Does Peter have a father?” We neither care whether he has one or many fathers nor who the father is:

?- isFatherOf(_,peter).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-9 R O O T S

Variables: Semantics

The scope of a variable is the clause in which it appears

isGrandfatherOf(G,C) :-isFatherOf(G F)clause in which it appears

Variables that appear only once

isFatherOf(G,F), isFatherOf(F,C).

isGrandfatherOf(G,Child) :-isFatherOf(G,M),pp y

in a clause are called singletons.Mostly results of typosSWI Prolog warns about

isMotherOf(M,Chil).

loves(romeo juliet)SWI Prolog warns about singletons, … unless you suppress the

i

loves(romeo,juliet).loves(john,eve).loves(jesus,Everybody).

warnings

All occurrences of the same ?- classDefT(ID, _, ‘Applet’, _).

variable in the same clause must have the same value!

Exception: the “anonymous

_Everybody

Intentional singleton variable, for which singleton warnings

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-10 R O O T S

Exception: the anonymous variable” (the underscore)

for which singleton warningsshould be supressed.

Constants

Numbers -17 -2.67e+021 0 1 99.9 512At f l tt di it d h t ' ' th tAtoms sequences of letters, digits or underscore characters '_' that

start with a lower case letter OROR

are enclosed in simple quotes ( ' ). If simple quotes should be part of an atom they must be doubled.

ORORonly contains special characters

k t ' F it ' k 'I d ''t k !'ok: peter ' Fritz ' new_york :- --> 'I don''t know!'

wrong: Fritz new-york _xyz 123

Remember: Prolog has no static typing!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-12 R O O T S

Function Terms (‘Structures’)

Function terms (structures) are terms that are composed of other termski t “ d ” i P l ( bj t ith t b h i i J )akin to “records” in Pascal (or objects without any behavior in Java)

functor subterms

person(peter, mueller, date(27,11,2007))

A bi i ll d

functor subterms

Arbitrary nesting allowedNo static typing: person(1,2,'a') is legal!Function terms are not function calls! They do not yield a result!!!Function terms are not function calls! They do not yield a result!!!

Notation for function symbols: Functor/Arity, e.g. person/3, date/3

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-13 R O O T S

Using Function Terms as Data Types

Function terms are the only “data constructor” in Prolog I j ti ith i di t t t bit ilIn conjunction with recursive predicates, one can construct arbitrarily deep structures

binary tree(empty)binary_tree(empty).binary_tree(tree(Left,Element,Right)) :-

binary_tree(Left), binary_tree(Right). recursive definition of „binary tree“ data type_

?- binary_tree( Any ).?- binary_tree( tree(empty,1,Right) ).

„ y yp

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-14 R O O T S

Lists – Recursive Structures with special SyntaxSyntax

Lists are denoted by square brackets "[]"

The pipe symbol "|" delimits the initial elements of the list from its tail“

[] [1,2,a] [1,[2,a],c]

The pipe symbol | delimits the initial elements of the list from its „tail

[1|[2,a]] [1,2|[a]] [Head|Tail]

Lists are just a shorthand for the binary functor ‘.’

[1,2,a] = .(1,.(2,.(a,[])))

You can define your own list-like data structure like this:

[ , , ] ( , ( , ( ,[])))

mylist( nil ).mylist( list(Head,Tail) ) :- mylist( Tail ).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-15 R O O T S

Strings

Strings are enclosed in double quotes (")" l " i t i"Prolog" is a string'Prolog' is an atomProlog (without any quotes) is a variable

A string is just a list of ASCII codes"Prolog" = [80,114,111,108,111,103]

= .(80,.(114,.(111,.(108,.(111,.(103,[])))))

Strings are seldom useful Better use atoms!There are many predefined predicates for manipulating atoms the same y p p p gway as Java uses strings.Prolog strings are useful just for low level manipulationTheir removal from the language has often been suggested

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-16 R O O T S

Their removal from the language has often been suggested

Terms, again

Terms are constanten, variables or structures

peter2727MM[europa, asien, afrika | Rest]person(peter, Nachname, date(27, MM, 2007))

A ground term is a variable free term

person(peter, mueller, date(27, 11, 2007))

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-17 R O O T S

Terms: Summary

Relations between the four different kinds of term

Term

Simple Term Function Term

Constant Variable Functor Arguments

Number Atom

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-18 R O O T S

Operators

Operators are just syntactic sugar for function terms: 1 3*4 i th i fi t ti f (1 *(3 4))1+3*4 is the infix notation for +(1,*(3,4))head :- body is the infix notation for ':-'(head,body)? goal is the prefix notation for '? '(goal)?- goal is the prefix notation for ?- (goal)

Operator declarations define notation, associativity and precedence:“f” position of functor“x” argument with precedence strictly lower than the functor

non‐associative side

“y” argument with precedence equal or lower than the functor

prefix notation associative side

:- op(1200, fx, '?-').

:- op( 500, yfx, '+'). ‘?‐’ has higher precedence than ‘+’

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-19 R O O T S

infix notation, left associative

Operator Associativity In Java, the assignment operator is right-associative. That is, the statement "a = b = c;" is equivalent to

"(a = (b = c));" It first assigns the value of c to b then

Left associative operators Right associative operators

(a = (b = c)); . It first assigns the value of c to b, then assigns the value of b to a.

Declaration Declaration

are applied in left-to-right order1+2+3 = ((1+2)+3)

are applied in right-to-left ordera,b,c = (a,(b,c))

Declaration Declaration:- op(500, yfx, '+'). :- op(1000, xfy, ',').

Effect Effect?- T = 1+2+3, T = A+B.T = 1+2+3,

?- T = (a,b,c), T =(A,B).T = (a b c)T 1+2+3,

A = 1+2,B = 3.

T = (a,b,c),A = a,B = (b,c).

Structure of term Structure of term

3++

,a,

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-20 R O O T S

21 cb

Operator Associativity

Non-associative operatorst b li itl b k t d

Associative prefix operatorsb d d

Declaration

must be explicitly bracketed

Declaration

may be cascaded

:- op( 700, xfx, '=').

:- op(1150, fx, dynamic).

:- op( 700, fy, '+').

:- op(1150, fy, '-').

Effect

?- A=B=C.Syntax error:

Effect

anything(_).?- anything(+ - + 1)Syntax error:

Operator priority clash? anything(+ + 1).true.

anything( )

Three associative

prefix t !?- A=(B=C).

A = (B=C).

anything(_).?- anything(+-+ 1).Syntax error: Operator expected

One atom, not three

operators!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-21 R O O T S

operators!

Example from page 5 rewritten using infix operatorsinfix operators

% Declare infix operators::- op(500 xfy isFatherOf): op(500,xfy,isFatherOf). :- op(500,xfy,isMotherOf). :- op(500,xfy,isGrandfatherOf).

% Declare predicates using the operator notation:kurt isFatherOf peter. peter isFatherOf paul.peter isFatherOf hans.peter isFatherOf hans.

G isGrandfatherOf C :- G isFatherOf F, F isFatherOf C.G isGrandfatherOf C :- G isFatherOf M, M isMotherOf C.

% Ask goals using the operator notation:?- kurt isGrandfatherOf paul.?- kurt isGrandfatherOf C.? kurt isGrandfatherOf C.?- isGrandfatherOf(G,paul).?- isGrandfatherOf(G,paul), X isFatherOf G.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-22 R O O T S

any combination of function term notation with operator notation is legal

Chapter 2: Syntax and Semantics

Operational Semantics

EqualityVariable bindings, Substitutions, Unification

Most general unifiersSLD-Resolution

Negation as failure

R O O T S

Equality (1)

Testing equality of terms

?- europe = europe. yes

?- 5 = 2. no

?- 5 = 2 + 3. no

?- 2 + 3 = +(2, 3). yes

Terms are not evaluated!

Terms are equal if they are structurally equal!!

Structural equality for ground terms: Constants are just Structural equality for ground terms:functors are equal and …… all argument values in the same position are structurally equal.

jfunctors with zero

arity!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-24 R O O T S

Equality (2)

Testing equality of terms with variables:

?- person(peter, Name, date(27, 11, 2007))

=

person(peter mueller date(27 MM 2007))

Whether these terms are equal depends on the values of the variables.

person(peter, mueller, date(27, MM, 2007)) .

IdeaA variable can take on any valueA variable can take on any value

For instance, mueller for Name and 11 for MMAfter this substitution, the terms are equal.

Equality test succeeds if there is a substitution that makes the terms equal!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-25 R O O T S

Equality in Prolog is “Unifiability”!

Testing equality of terms with variables:

?- person(peter, Name, date(27, 11, 2007))

=

person(peter mueller date(27 MM 2007))

Whether these terms are equal depends on the values of the variables.

person(peter, mueller, date(27, MM, 2007)) .

Prolog TerminologyA variable can be bound to any termA variable can be bound to any term

Two sample bindings: Name ← mueller and MM ← 11

A substitution is a set of bindingsA sample substitution: {Name ← mueller, MM ← 11}

A unifier is a substitution that makes two terms equalTerms T1 and T2 are equal if they are unifiable (they have a unifier)!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-26 R O O T S

Terms T1 and T2 are equal if they are unifiable (they have a unifier)!

Unification (1)

Can you find out the unifiers for these terms?

date(1, 4, 1985) = date(1, 4, Year)

d t (D M th 1985) d t (1 4 Y )

{Year← 1985}

{ 1985 h 4}date(Day, Month, 1985) = date(1, 4, Year)

a(b,C,d(e,F,g(h,i,J))) = a(B,c,d(E,f,g(H,i,j)))

[[the Y]|Z] = [[X dog] [is here]]

{Year← 1985, Month ← 4}

{B ←b, C ←c, …, J ← j}

[[the, Y]|Z] = [[X, dog], [is, here]]

X = Y + 1

{Y ← dog, Z ← [is,here]}

{X ← Y+1}

But what about

p(X) = p(q(X)) {X ← q(X)}

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-27 R O O T S

produces a cyclic substitution

Application of a Substitution to a Term (1)(1)

Substitutions are denoted by greek letters: γ, σ, τFor instance: γ = {Year ← 1985, Month ← 4}

Application of a substitution τ = {V ← t V ← t } to a term TApplication of a substitution τ = {V1 ← t1, …, Vn ← tn} to a term T

is written Tτ

date(Day Month 1985)γdate(Day,Month,1985)γ

X=Y+1{X ← Y+1}

f(X,1){Y←2,X←g(Y)}

replaces all the occurrences of Vi in T by tiτ, for i = 1..n.

date(Day,Month,1985)γ ≡ date(Day,4,1985)

X=Y+1{X ← Y+1} ≡ Y+1=Y+1

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-28 R O O T S

f(X,1){Y←2,X←g(Y)} ≡ f(g(2),1)

Application of a Substitution to a Term (2)(2)

ImportantF {V t V t } d i 1For τ = {V1 ← t1,…,Vn ← tn} and i = 1..n

Tτ replaces all the occurrences of Vi in T by tiτ.

Substitutions are applied to their own right‐hand‐sides too!

R lti P bl

f(X,1){Y←2,X←g(Y)} ≡ f(g(2),1)

Resulting ProblemApplication of cyclic bindings creates infinite terms

Prevention: Don’t create cyclic substitutions in the first place!

p(X){X ← q(X)} ≡ f(f(f(f(f(f(f(f(f(...)...)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-29 R O O T S

y p“Occurs Check” verifies whether unification would create cyclic substitutions

„Occurs Check“ (1)

TheoryU ifi ti t f il if it ld t b tit ti ith li bi diUnification must fail if it would create substitutions with cyclic bindings

p(X) = p(q(X)) // must fail

ProblemUnification with “occurs-check” has exponential worst-case run-timepUnification without “occurs-check” has linear worst-case run-time

Practical Prolog implementationsProlog implementations do not perform the occurs check

… unless you explicitly ask for itp(X) = p(q(X)) // succeeds

unify with occurs check(p(X) p(q(X)) ) // fails

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-30 R O O T S

unify_with_occurs_check(p(X), p(q(X)) ) // fails

„Occurs Check“ (2)

No occurs check when binding a variable to another term

circular binding is flagged (**)

?- X=f(X).X = f(**).

i ti f i fiti t t t i t

?- X=f(X), write(X).... printing of infitinte term never terminates ...

printing of infitinte term never terminates

?- X=f(X), X=a.fail.

Circular reference is checked by second unification, so the goal fails gracefully

SWI-Prolog has an occurs-check version of unification available ?- unify_with_occurs_check(X,f(X)).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-31 R O O T S

fail.

Unification (2)

Unification of terms T1 and T2fi d b tit ti f th i bl f T1 d T2 h th tfinds a substitution σ for the variables of T1 and T2 such that …… if σ is applied to T1 and T2 then the results are equal

Unification satisfies equations ?- p(X,f(Y),a) = p(a,f(a),Y).X = a, Y = a.

?- p(X,f(Y),a) = p(a,f(b),Y).

QuestionHow to unify two variables?

Problem: Infinitely many unifying?- p(X) = p(Z).X a Y a;

fail.

Problem: Infinitely many unifying substitutions possible!!!

Solution

X = a, Y = a;X = b, Y = b;…

Unification finds the most generalunifying substitution

“most general unifier” (mgu)

?- p(X) = p(Z).X = _G800, Y = _G800;true.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-32 R O O T S

most general unifier (mgu) true.

Unification yields Most General Unifier (MGU)(MGU)

Unification of terms T1 and T2fi d th t l b tit ti f th i bl f T1 d T2 hfinds the most general substitution σ for the variables of T1 and T2 such that …… if σ is applied to T1 and T2 then the results are equal

Theorem (Uniqueness of MGU): The most general unifier of two terms T1 and T2 is uniquely determined up to renaming of variablesand T2 is uniquely determined, up to renaming of variables.

If there are two different most general unifiers of T1 and T2, say σ andthen there is also a renaming substitution such that τ, then there is also a renaming substitution γ such that

A renaming substitution only binds variables to variables

T1σγ ≡ T2τ

f(Y){Y←Z, Z←_G200} ≡ f(_G200)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-33 R O O T S

Computing the Most General Unifiermgu(T1 T2)mgu(T1,T2)

Input: two terms, T1 and T2

Output: the most general unifier of T and TOutput: σ, the most general unifier of T1 and T2(only if T1 and T2 are unifiable)

Algorithm1. If T1 and T2 are the same constant or variable then σ = { } 2. If T1 is a variable not occurring in T2 then σ = {T1 ← T2} 3 If T is a ariable not occ ring in T then {T T }3. If T2 is a variable not occuring in T1 then σ = {T2 ← T1}4. If T1 = f(T11,...,T1n) and T2 = f(T21,...,T2n) are function terms with the same

functor and arity1. Determine σ1= mgu(T11, T21)2. Determine σ2= mgu(T11σ1, T21σ1)3. . . .4. Determine σn= mgu(T1nσ1…σn-1, T2nσ1…σn-1)5. If all unifiers exist then σ = σ1…σn-1σn

(otherwise T1 and T2 are not unifiable)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-34 R O O T S

(ot e se 1 a d 2 a e ot u ab e)5. Occurs check: If σ is cyclic fail, else return σ

„Advanced Logic Programming“Summer semester 2009 R O O T SSu e se es e 009

Chapter 2 Chapter 2. Prolog Syntax and Semantics

SyntaxModel-theoretic semantics (“Logical Consequence”)

Operational semantics (“Derivation / Resolution”)

Why is unification so important?

Unification is the basic operation p

of any Prolog interpreter.

Resolution is the process by which Prolog derives answers (successful substitutions) for queries

During resolution, clauses that can be used to prove a goal are determined via unification

?- isFatherOf(paul,Child).

i F th Of( F C ) i M i dT (F M) i M th Of(M C)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-39 R O O T S

isFatherOf( F , C ) :- isMarriedTo(F,M), isMotherOf(M,C).

Resolution

Resolution PrincipleThe proof of the goal ?- P, L, Q.

can be reduced to prooving ?- Pσ, L1σ, ... , Lnσ, Qσ.

if there exists a clause L0:- L1, ..., Ln (n≥0)

such that σ = mgu(L,L0)

Graphical illustration of resolution by “derivation trees”

? P L QInitial goal

L0:- L1, L2, ..., Ln

?- P, L, Q.

Copy of clause with renamed variables(different from variables in goal!)

Initial goal

?- Pσ, L1σ, ... , Lnσ, Qσ.

σ = mgu(L,L0)Unifier of selected literal and clause head

Derived goal

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-40 R O O T S

Resolution reduces goals to subgoals

For “Goal2 results from Goal1 by resolution”

we also say “Goal2 is derived from Goal1”

or “Goal1 is reducible to Goal2”and write “Goal1 s Goal2”

? P L QGoal / Goal ?- P, L, Q.Goal / Goal1

Derivation / reduction step

?- Pσ, L1σ, ... , Lnσ, Qσ.Subgoal / Goal2

/ p

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-41 R O O T S

Resolution: Example (1)

Program

isMotherOf(maria, klara).isMotherOf(maria, paul).isMotherOf(eva, anna).

isMarriedTo(paul, eva).

isGrandmaOf(G, E) :-isMotherOf(G, M), isMotherOf(M, E).

isGrandmaOf(G, E) :-isMotherOf(G V) isFatherOf(V E)isMotherOf(G, V), isFatherOf(V, E).

isFatherOf(V, K) :-isMarriedTo(V, M), isMotherOf(M,K).

...

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-42 R O O T S

Resolution: Example (2)

i G d Of(G1 E1) i M th Of(G1 V1) i F th Of(V1 E1)

?- isGrandmaOf(maria,Granddaughter).

isGrandmaOf(G1, E1) :- isMotherOf(G1, V1),isFatherOf(V1, E1).σ1 = {G1←maria, E1←Granddaughter}

?- isMotherOf(maria,V1),isFatherOf(V1,Granddaughter).

isMotherOf(maria, paul).σ2 = {V1←paul}

?- isFatherOf(paul,Granddaughter).

isFatherOf(V2, K2) :- isMarriedTo(V2, M2),isMotherOf(M2, K2).σ3 = {V2←paul, K2←Granddaughter}

?- isMarriedTo(paul M2) isMotherOf(M2 Granddaughter)

isMarriedTo(paul, eva).σ4 = {M2←eva}

?- isMarriedTo(paul,M2),isMotherOf(M2,Granddaughter).

isMotherOf(eva, anna).σ5 = {Granddaughter ← anna}

?- isMotherOf(eva,Granddaughter).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-43 R O O T S

Resolution: Example (3)

The result is the composition of all substitutions computed along a derivation pathderivation path

σ1 = {G1←maria, E1←Granddaughter}

σ2 = {V1←paul}2 { p }

σ3 = {V2←paul, K2←Granddaughter}

σ4 = {M2←eva}

σ = {Granddaughter ← anna}σ5 = {Granddaughter ← anna}

σ1 σ2 σ3 σ4 σ5 ={G1←maria, E1←Granddaughter, V1←paul, V2←paul, K2←Granddaughter, M2←eva, Granddaughter ← anna}

… restricted to the bindings for variables from the initial goal

σ = σ1 σ2 σ3 σ4 σ5 | Vars( isGrandmaOf(maria,Granddaughter) )= σ1 σ2 σ3 σ4 σ5 | { Granddaughter }

{G dd ht }

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-44 R O O T S

= {Granddaughter ← anna}

Note: One can also bind differently!

The result is the composition of all substitutions computed along a derivation pathderivation path

σ1 = {G1←maria, Granddaughter←E1}

σ2 = {V1←paul}2 { p }

σ3 = {V2←paul, E1←K2}

σ4 = {M2←eva}

σ = {K2←anna}

No, because during composition, later

substitutions are applied to the previous ones!

Wouldn’t that yield another result?

Wouldn’t that yield another result?

Different bindings than on the previous page!

Does that mean we geta different result???σ5 = {K2←anna}

σ1 σ2 σ3 σ4 σ5 ={G1←maria, Granddaughter←anna, V1←paul, V2←paul, E1←anna, M2←eva, K2←anna}

to the previous ones!a different result???

… restricted to the bindings for variables from the initial goal

σ = σ1 σ2 σ3 σ4 σ5 | Vars( isGrandmaOf(maria,Granddaughter) )= σ1 σ2 σ3 σ4 σ5 | { Granddaughter }

{G dd ht }= {Granddaughter←anna}Same result substitution as on the previous page!

Chapter 2: Syntax and Semantics

Operational Semantics (cont.)

OK, we’ve seen how resolution finds one answer. But what how to find more answers?

Backtracking!

R O O T S

Derivation with Backtracking

f(a). g(a).

f(b). g(b). h(b).

?- f(X), g(X), h(X).

#1, X=a choicepoint: #2

?- g(a), h(a).

#1 choicepoint: #2

?- f(Y), g(Y), h(Y).?- h(a).

#1 choicepoint: #2

The subgoal h(a) fails because there is noThe subgoal h(a) fails because there is no clause whose head unifies with it.The interpreter backtracks to the last “choicepoint” for g(a)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-47 R O O T S

choicepoint for g(a)

Derivation with Backtracking

f(a). g(a).

f(b). g(b). h(b).

?- f(X), g(X), h(X).

#1, X=a choicepoint: #2

?- g(a), h(a).

?- f(Y), g(Y), h(Y).

The subgoal g(a) fails because there is no remaining clause (at the choicepoint or after it) whose head unifies with it.The interpreter backtracks to the last

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-48 R O O T S

“choicepoint” for f(X)

Derivation with Backtracking

f(a). g(a).

f(b). g(b). h(b).

?- f(X), g(X), h(X).

#2, X=b choicepoint: ---

?- g(b), h(b).

#2 choicepoint:

?- f(Y), g(Y), h(Y).

#2 choicepoint: ---

?- h(b).

Y=b;no

?- true.

#1 choicepoint: ---

The derivation is successful (it derived the subgoal “true”).The interpreter reports the successful

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-49 R O O T S

The interpreter reports the successful substitutions

SLD-Resolution with Backtracking: SummarySummary

SLD-Resolution always selects theth l ft t lit l i l did t f b i l dthe leftmost literal in a goal as a candidate for being resolvedthe topmost clause of a predicate definition as a candidate for resolving the current goal

If a clause’s head is not unifiable with the current goal the search proceeds immediately to the next clause

If a clause’s head is unifiable with the current goalthe goal is resolved with that clausethe interpeter remembers the next clause as a choicepoint

If no clause is found for a goal (= the goal fails), the interpreter undoes the current derivation up to the last choicepoint .

Then the search for a candidate clause continues from the choicepoint

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-50 R O O T S

Box-Model of Backtracking

A goal is a box with four ports: call, succeed, redo, failNested goals (subgoals) are boxes nested within the own box withNested goals (subgoals) are boxes nested within the own box, with ports of the same kind connected (outer call to inner call, …)

call succeed

g

For chained goals (conjunction)

redofail

For chained goals (conjunction)the “succeed” port is connected to the “call” port of the next goal and the “fail” port is connected to the “redo” port of the previous

call succeed

g1

call succeed

gn…

redofail

g1

redofail

gn…

Viewing Backtracking in the Debugger (1)(1)

?- gtrace, simplify_aexpr(a-a+b-b, Simple).call the graphical tracer … for this goal.g p…

g

goals without choice pointsreference to next

choice point

variable bindings in selected stack frame

goals with choice points

call of “built-in”

c o ce po t

call of built inpredicate (hasno choicepoint)

source code view of goal associated to

the only exceptionassociated to

selected stack frame

exceptionis “repeat”

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-52 R O O T S

Viewing Backtracking in the Debugger (2)(2)

The debugger visualizes the port of the current goal according to the box model.

call succeed

gg p g g

df il

g

redofail

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-53 R O O T S

Recursion

Prolog predicates may be defined recursively

A predicate is recursive if one or more rules in its definition refer to itself.descend(X,Y):- child(X,Y).

descend(X,Y):- child(X,Z), descend(Z,Y).

What does this mean?What does this mean? 1. if Y is a child of X, then Y is a descendant of X2. if Z is a child of X, and Y is a descendant of Z, then Y is a descendant of X

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-54 R O O T S

Recursion: Derivaton Tree for “descend”

child(martha, charlotte).descendant #1

descend(martha,laura)

child(charlotte, caroline).

child(caroline, laura).

child(laura, rose).

descendant  #1

descendant  #2child(martha,laura)

hild ( th Y1) d d(Y l )

descend(X,Y):- child(X,Y).

descend(X,Y):-child #1 :   { Y1←charlotte}

child (martha,Y1), descend(Y,laura)

descend(charlotte laura)child(X,Z),descend(Z,Y).descendant  #1

descendant  #2

descend(charlotte,laura)

child(charlotte,laura)

?- descend(martha, laura)yes

( , )

child (charlotte,Y2), descend(Y,laura)

child #2 :   { Y2←caroline}

descend(caroline,laura)descendant #1

☺ child(caroline,laura)

descendant  #1

child #3:   { }

Recursion: Successor

Suppose we want to express that0 i l0 is a numeralIf X is a numeral, then succ(X) is a numeral

numeral(0).

numeral(succ(X)) :- numeral(X).

Let’s see how this behaves:?- numeral(X).

X = 0 ;

X = succ(0) ;

X = succ(succ(0)) ;

X = succ(succ(succ(0))) ;

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-57 R O O T S

Chapter 2: Syntax and Semantics

Operational Semantics (cont.)

Can we prove truth or falsity of any goal?

No, unfortunately!

R O O T S

Incompleteness of SLD-Resolution

ProvabilityIf l b d d t th t b l th th l i blIf a goal can be reduced to the empty subgoal then the goal is provable.

UndecidabilityyThere is no automated proof system that always answers yes if a goal isprovable from the available clauses and answers no otherwise.Prolog answers yes no or does not terminateProlog answers yes, no or does not terminate.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-60 R O O T S

Incompleteness of SLD-Resolution

The evaluation strategy of Prolog is incomplete. B f t i ti d i ti P l ti l d iBecause of non-terminating derivations, Prolog sometimes only derives a subset of the logical consequences of a program.

Exampler, p, and q are logical consequences of this program p :- q. % 1

% 2q :- p. % 2 p :- r. % 3 r. % 4

However, Prolog’s evaluation strategy cannot derivethem. It loops indefinitely:

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-61 R O O T S

Chapter 2: Syntax and Semantics

Declarative Semantics

If resolution is limited then how do we know what a formula / goal / program means?

Translation of Prolog to logical formulasg gNormalization of logical formulas

Logical ConsequenceHerbrand Interpretations and Models

R O O T S

p

Question

Q tiQuestionWhat is the logical meaning of this program?

bigger(elephant, horse).

bigger(horse, donkey).gg y

is_bigger(X, Y) :- bigger(X, Y).

is_bigger(X, Y) :- bigger(X, Z), is_bigger(Z, Y).

Rephrased question: Two stepsH d thi t l t t l i f l ?1. How does this program translate to logic formulas?

2. What is the meaning of the logic formulas?

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-63 R O O T S

Translation of Programs

Each predicate remains the same (syntactically).

Each comma separating subgoals becomes ∧ (conjunction).

Each Head :- Body becomes Head ← Body or Body → Heady ← y y →(implication)

Each variable in the head of a clause is bound by a ∀y(universal quantifier)

son(X,Y) :- father(Y,X),male(X).

∀x.∀yEach variable that occurs only in the body of a clause is bound by a ∃Each variable that occurs only in the body of a clause is bound by a ∃(existential quantifier)

grandfather(X):- father(X,Y) , parent(Y,Z).

∀x. ∃y.∃z.

grandfather(X): father(X,Y) , parent(Y,Z).

Translation of Programs (cont.)

A P l i t l t d t t f f l ithA Prolog program is translated to a set of formulas, with each clause in the program corresponding to one formula:

{ bigger( elephant, horse ),bigger( horse, donkey ),∀x.∀y.( bigger(x, y) → is_bigger(x, y) ),∀x.∀y.( ∃z.(bigger(x, z) ∧ is_bigger(z, y)) → is_bigger(x, y) )

}

Such a set is to be interpreted as the conjunction of all the formulas inSuch a set is to be interpreted as the conjunction of all the formulas in the set.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-65 R O O T S

Normalization Steps

Start: Closed First Order Formula (FOF)“Cl d” th t h i bl i i th f ( “b d b ”)“Closed” means that each variable is in the scope of (= “bound by”) a quantifier.

1. Disjunct Variable Form (VDF)Rename variables bound by quantifiers so that they are unique!

2. Elementary Junctor Form (EJF)Reduce ⇒, ⇔, etc. to ∨, ∧ and ¬according to the following rules:

3 Negation form (NF)3. Negation form (NF)EJF and all negations in front of atomic formulas (= literals)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-66 R O O T S

according to the following rules:

Translation of Programs (cont.)

We illustrate the previous steps on a formula from our translated program:

A formula in Disjunct Variable Form

∀x.∀y.( ∃z.(bigger(x, z) ∧ is_bigger(z, y)) → is_bigger(x, y) )

Its Elementar J nctor Form isIts Elementary Junctor Form is

∀x.∀y.( ¬∃z.(bigger(x, z) ∧ is_bigger(z, y)) ∨ is_bigger(x, y) )

Its Negation Form is

∀x.∀y.( ∀z.¬(bigger(x, z) ∧ is_bigger(z, y)) ∨ is_bigger(x, y) ) ⇔

∀x.∀y.( ∀z.(¬bigger(x, z) ∨ ¬is_bigger(z, y)) ∨ is_bigger(x, y) ) .

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-67 R O O T S

Normalization Steps (cont.)

4. Prenex Normal Form (PNF): M ll tifi t th fi ( th l ft h d id ) di t th lMove all quantifiers to the prefix(= the left-hand-side) according to the rules:

if x not free in Φ if x not free in Φ

prefix if x not free in Φ

matrix

if x not free in Φ

if x not free in Φ

if x not free in Φ

if x not free in Φ

The matrix (= remaining right-hand-side part of formula) is quantifier-free

if x not free in Φ

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-68 R O O T S

The matrix ( remaining right hand side part of formula) is quantifier freeEach formula in VDF can be translated to PNF.

Translation of Programs (cont.)

We illustrate the PNF by continuing our example:

Its Negation Form was

∀x.∀y.( ∀z.(¬bigger(x, z) ∨ ¬is bigger(z, y)) ∨ is_bigger(x, y) ) .

Its Prene Normal Form isIts Prenex Normal Form is

∀x.∀y.( ∀z.(¬bigger(x, z) ∨ ¬is_bigger(z, y) ∨ ∀z.is_bigger(x, y) )

∀x.∀y.( ∀z.(¬bigger(x, z) ∨ ¬is_bigger(z, y) ∨ is_bigger(x, y)) )

∀x.∀y.∀z.(¬bigger(x, z) ∨ ¬is bigger(z, y) ∨ is bigger(x, y))∀x.∀y.∀z.(¬bigger(x, z) ∨ ¬is_bigger(z, y) ∨ is_bigger(x, y))

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-69 R O O T S

Normalization Steps (cont.)

4. Skolem Form (SF)R l i PNF f l ll f h i t ti l i bl bReplace in PNF formula all occurrences of each existential variable by a unique constant Skolemization does not preserve truth but preserves satisfiability. This is sufficient since resolution proves truth of F by proving unsatisfiabilityof ¬F.

5. Conjunctive Normal Form (CNF)Transform quantor-free matrix of formulas in PNF into a conjunction of di j ti f t t d tdisjunctions of atoms or negated atoms A formula can be translated to CNF if and only if it is quantor-free.

6. Clausal Form A formula in PNF, SF and with matrix in CNF is said to be in clausal form.E h j t f f l i l l f i l

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-70 R O O T S

Each conjunct of a formula in clausal form is one clause.

Translation of Programs (cont.)

Our previous example already was in Skolem form (no existential quantifiers)quantifiers).

Here is another formula, which is in Prenex but not Skolem form:Here is another formula, which is in Prenex but not Skolem form:

∃x∃v∀y∀w.(R(x,y) ∧ ¬R(w,v))

Its Skolem Form is

∀y∀w (R(c y) R(w c ))∀y∀w.(R(c1,y) ∧ ¬R(w,c2))

Skolem form is often written without quantifiers, abusing the implicitSkolem form is often written without quantifiers, abusing the implicit knowledge that all variables are universally quantified

R(c1,y) ∧ ¬R(w,c2)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-71 R O O T S

R(c1,y) ∧ ¬R(w,c2)

Horn Clauses

The formulas we get when translating all have the same structure:

A1 ∧ A2 ∧ · · · ∧ An → B

Such a formula can be rewritten as follows:

A1 ∧ A2 ∧ · · · ∧ An → B by law A → B ≡ ¬A ∨ B we getA1 ∧ A2 ∧ ∧ An → B by law A → B ≡ A ∨ B we get¬(A1 ∧ A2 ∧ · · · ∧ An) ∨ B by law ¬(A∧B) ≡ ¬A ∨ ¬B we get¬A1 ∨ ¬A2 ∨ · · · ∨ ¬An ∨ B

Hence, Prolog clauses can always translated as disjunctions of ti lit l ith t t iti lit lnegative literals with at most one positive literal.

These are know as Horn clauses

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-72 R O O T S

These are know as Horn clauses.

Translation of Programs (cont.)

Thi i P l itt t f H ClThis is our Prolog program written as a set of Horn Clauses:

{ bigger( elephant, horse ),bigger( horse, donkey ), ∀x.∀y.( ¬bigger(x, y) ∨ is_bigger(x, y) ),∀x.∀y.∀z.(¬bigger(x, z) ∨ ¬is_bigger(z, y) ∨ is_bigger(x, y))

}

Such a set is to be interpreted as the conjunction of all the formulas in the set.

SLD-Resolution is only applicable to Horn Clauses

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-73 R O O T S

Translation of Queries: Basics

Undecidability of first order logicTh i t t d f t th t l if l iThere is no automated proof system that always answers yes if a goal isprovable from the available clauses and answers no otherwise.

Semi-decidability of first order logicIt is possible to determine unsatisfiability of a formula by showing that itleads to a contradiction (an empty clause)leads to a contradiction (an empty clause)

Implication of Semi-DecidabilityWe cannot prove a goal directly but must show that adding the negation of the goal to the program P makes P unsatisfiable

P s G is proven by showing that (P ∪ ¬G) s {}

Proving a formula by showing that its negation is wrong is called proofby refutation.

Translation of Queries

The query

?- is_bigger(elephant, X), is_bigger(X, donkey).

corresponds to the formulas

∀∀x.( ¬(is_bigger(elephant, x) ∧ is_bigger(x, donkey) )

∀x.( ¬is_bigger(elephant, x) ∨ ¬is_bigger(x, donkey) )

∀x.( ¬(is_bigger(elephant, x) ∧ is_bigger(x, donkey) ) → false

and to the ruleand to the rule

fail :- is_bigger(elephant, X), is_bigger(X, donkey).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-75 R O O T S

Proof by Refutation via Resolution

Formula that we want to prove

Neg

a

Its negation

atio

n

Variable Disjunct Form

Elementary Junctor Form

N

possible(w

hich onlElementary Junctor Form

Prenex Normal Form

orm

aliza

e for all closely contain vaby quantifie

Skolemized Form (implicit ∀)

(H ) Cl F (i li it ∀)

tion

ed formulas 

ariables bouners)

(Horn) Clause Form (implicit ∀)

Unification with mgu {w←c y←c }

Ref

  nd 

Unification with mgu {w←c0, y←c1}

Resolution of clause 2 with clause 1 {}

futa

tion

Chapter 2: Syntax and Semantics

What is the Meaning of a Formula?

Why Resolution isn’t enoughInterpretations of formulasp

Herbrand InterpretationsHerbrand Model

R O O T S

What is the Meaning of a Formula?

Now k h t t l t P l t H Clwe know how to translate Prolog programs to Horn Clauses

we know that SLD resolution is applicable to Horn Clauses

But we had noticed previously that SLD resolution is incomplete

t ll l ki f lt ti t i i t P lwe were actually looking for an alternative way to give meaning to Prolog programs

QuestionWhy all that stuff about translation and normalization?

AnswerThere is an alternative semantics for the translated logic formulas

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-80 R O O T S

… and it is independent of proof algorithms such as resolution.

Interpretations of Formulas

A An An A formula

An interpretation

domain

An Interpretation

loves: Man × Woman → Bool

loves ( john , mary )

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-81 R O O T S

Interpretations of Formulas

Same Slightly differentSlightly different Same formula

Slightly differentinterpretation

domain

Slightly different Interpretation

loves: Person × Person → Bool

loves ( john , mary )

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-82 R O O T S

Interpretations of Formulas

Same Other Other Sameformula

Other interpretation

domain

Other Interpretation

$$ $ $

$targetOf: Spy × Secret → Bool

loves ( john , mary )

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-83 R O O T S

Interpretations of Formulas

A Our initial An A formula

Our initial interpretation

domain

An Interpretation

loves: Man × Woman → Bool

brlbzqf( prfkz , flurp )

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-84 R O O T S

What does this tell us?

Ob tiObservations

Formulas only have a meaning with respect to an interpretation

An interpretation maps formulas to elements of an interpretation domain

constants to constant in the domain “john” to

function symbols to functions on the domainlno example

predicates to relations on the domain“loves/2” to “targetOf: Spy × Secret → Bool”o es/ to ta getO Spy Sec et → oo

formulas to truth values“loves(john,mary)” to “true”

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-85 R O O T S

What does this tell us?

Dilemma

Too many possible interpretions!

Which interpretation to use for proving truth?Which interpretation to use for proving truth?

Solution

For universally quantified formulas there is a “standard” interpretation, the “Herbrand interpretation” that has two nice properties:

If any interpretation satisfies a given set of clauses Sthen there is a Herbrand interpretation that satisfies them

It suffices to check satisfiability for the Herbrand interpretationIt suffices to check satisfiability for the Herbrand interpretation

If S is unsatisfiable then there is a finite unsatisfiable set of ground instances from the Herbrand base defined by S.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-86 R O O T S

Unsatisfiability can be checked finitely

Herbrand Interpretations

FormulaHerbrand

Interpretation

D = Interpretation

Interpretation

{ p: HU×HU → true } = Pred

{ c1 , c2 } = Const domain

{ , }{ f/1 } = Func

c1c2

f(c1)

HU = Herbrand Universe

all ground terms in D

p( c1 , f ( c2 ) )

( )= all ground terms in D

f(c2)

H b d ( 1 1) ( )

predicatef t

Herbrand Base

= all positive 

D

p(c1, c1)p(c1, c2)p(c1, f(c1))p(c1 f(c2))

p(c2, c1)p(c2, c2)p(c2, f(c1))p(c2 f(c2))

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-87 R O O T S

constantfunctor ground literals in Dp(c1, f(c2)) p(c2, f(c2))

Herbrand Interpretations of Formulas with VariablesVariables

FormulaHerbrand

Interpretation

D = Interpretation

Interpretation

{ p: HU×HU → true } = Pred

{ c1 , c2 } = Const domain

{ , }{ f/1 } = Func

c1c2

f(c1)

HU = Herbrand Universe

all ground terms in D

p( c1, f ( X ), c2 )

( )= all ground terms in D

f(c2)

H b d ( 1 1 2) ( )

XHerbrand

Base= all positive 

D

p(c1, c1,c2)p(c1, c2,c2)p(c1, f(c1),c2)p(c1 f(c2) c2)

p(c2, c1,c1)p(c2, c2,c1)p(c2, f(c1),c1)p(c2 f(c2) c1)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-88 R O O T S

ground literals in Dp(c1, f(c2),c2) p(c2, f(c2),c1)

Herbrand Modells

The Interpretation Domain (D) of a program P consists of three sets:The Interpretation Domain (D) of a program P consists of three sets: Const contains all constants occurring in PFunc contains all function symbols occurring in PPred contains a predicate p: HUxHU true for each predicate symbol poccurring in the program P

The Herbrand Universe (HU) of a program P is the set of all ground terms that can be constructed from the function symbols and constants in P

The Herbrand Base of a program P is the set of all positive ground literals that can be constructed by applying the predicate symbols in Pliterals that can be constructed by applying the predicate symbols in P to arguments from the Herbrand Universe of P

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-89 R O O T S

Herbrand Models

A Herbrand Interpretation maps each formula in P to the elements ofA Herbrand Interpretation maps each formula in P to the elements of the Herbrand Base that are its logical consequences

Each ground fact is mapped to true.Each possible ground instantiation of a non-ground fact is mapped to true.Each instantiation of the head literal of a rule that is a logical consequence of the rule body is mapped to true

The Herbrand Model of a program P is the subset of the Herbrand Base of P that is true according to the Herbrand Interpretation. g p

The Herbrand Model can be constructed by fixpoint iteration:Initialize the model with the ground instantiations of facts in PAdd all new facts that follow from the intermediate model and P

until the model does not change anymore (= fixpoint is reached)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-90 R O O T S

… until the model does not change anymore (= fixpoint is reached)

Constructing Models by Fixpoint Iteration

Program Model Fixpoint gp :- q. % 1 q :- p. % 2 p :- r. % 3 r. r. r. r.

M0 M1 M2 M3 M4=M3

pr. % 4

r. r.p.

r.p.q.

r.p.q.

r. % r

r. % rp :- r. % p

r. % rp :- r. % p q :- p. % qClauses

r. % rp :- r. % p q :- p. % q

contributing model elementsin the respective iteration

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-91 R O O T S

q p qp :- q. % p

in the respective iteration

Two different ways to give meaning to logic programs

Operational Semantics Declarative Semantics

logic programs

p

Proof-based approachAlgorithm to find a proof

Model-based semanticsMathematical structure

Refutation proof using SLD resolutionBasic step: Derivation

Herbrand interpretations and Herbrand modelsBasic step: EntailmentBasic step: Derivation

To prove a goal prove each of

Basic step: Entailment (Logical consequence)

A formula is true if it is a logicalTo prove a goal prove each of its subgoals

A formula is true if it is a logical consequence of the program

Algorithm = Logic + ControlLogic = ClausesControl = Top-down resolution

Algorithm = Logic + ControlLogic = ClausesControl = Bottom up fixpoint

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-92 R O O T S

Control = Top-down resolution process

Control = Bottom-up fixpoint iteration

Practical Implications

Need to understand both semanticsTh d l b d (d l ti ) ti i th “ f ”The model-based (declarative) semantics is the “reference”

We can apply bottom-up fixpoint iteration to understand the set of logical consequences of our programs

The proof-based (operational) semantics is the one Prolog uses to prove that a goal is among the logical consequences

SLD-derivations can get stuck in infinite loops, missing some correct results

Need to understand when these semantics differWhen do Prolog programs fail to terminate?

Order of goals and clausesOrder of goals and clausesRecursion and “growing” function termsRecursion and loops in data

Which other problems could prevent the operational semantics match the declarative semantics?

The cut!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-93 R O O T S

Non-logical features…

General Principles

Try to match both semantics!Try to match both semantics!Your programs will be more easy to understand and maintain

Write programs with the model-based semantics in mind!If they do not behave as intended change them so that they do!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-94 R O O T S

Chapter 2: Syntax and Semantics

Practical Implications (Part 1)

Order of goals and clausesRecursion and cyclic predicate definitions

Recursion and cycles in the dataRecursion and “growing” function terms

R O O T S

Order of Clauses in Predicate Definition

Ensure termination of recursive definitions by putting non-recursive clausesbefore recursive ones!before recursive ones!

Loops infinitely for ?-p: ?-p succeeds infinitely often:Loops infinitely for ? p: ? p succeeds infinitely often:p :- q. % 1 p :- r. % 2 q :- p. % 3

p :- r. % 1 p :- q. % 2 q :- p. % 3

In spite of same

Herbrand r. % 4 r. % 4

r.p.q

Model:

Traces:?- p. ?- p.

q.

... nothing happens

...true ;true ;...

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-96 R O O T S

Order of Literals in Clause

Ensure termination of recursive definitions by putting non-recursive goalsbefore recursive ones!before recursive ones!

Succeeds twice and then Succeeds exactly twiceSucceeds twice and then Succeeds exactly twiceloops infinitely for ?-p(X): for ?-p(X): p(0). (X) (Y) (X Y)

p(0). (X) (X Y) (Y)

In spite of same

Herbrand

Traces:

p(X) :- p(Y), a(X,Y). a(1,0).

p(X) :- a(X,Y), p(Y).a(1,0). p(0).

p(1).(1 0)

Model:

Traces:

?- p(X). ?- p(X).

a(1,0).

X = 0 ;X = 1 ;ERROR: Out of local t k

X = 0 ;X = 1 ;false.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-97 R O O T S

stack

Finding Paths (1)

Given: The following floor plan … or its graph representation

a b c a b c

d e f d e f

A possible Prolog representation: … for a directed graphdoor(a,b). door(b c) a b cdoor(b,c). door(b,d). door(c,e).door(c,f).

d e f

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-98 R O O T S

door(d,e).door(e,f).

d e f

Finding Paths (2)a b c

d e f

Question: How to represent symmetry of doors?

d e f

door(a,b). door(b,c). door(b,d).

door(c,f).door(d,e).door(e,f).

a b c

door(b,d). door(c,e).

door(e,f).

d e f

1. Attempt: Recursive definition

door(X Y) : door(Y X) X Y

door

2 Att t S lit d fi iti i t t di t

door(X, Y) :- door(Y, X). X Y

door

2. Attempt: Split definition into two predicates

connected(X, Y) :- door(X, Y).connected(Y X) doo (X Y)

X Y

connected

X Y

door

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-99 R O O T S

connected(Y, X) :- door(X, Y).connected

Finding Paths (3)a b c

d e f

Question: Is there a path from room X to room Y?

d e f

1. Attempt: connected(X Y) :- door(X Y)connected(X, Y) :- door(X, Y).connected(X, Y) :- door(Y, X).

path(X, Y) :- connected(X, Y).th(X Y) t d(X Z) th(Z Y)

Declaratively OK, but will loop on cycles induced by definition of connected/2!

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

connected/2!Derives the same facts infinitely often:?- path(X,Y).X = a, Y = b ; ...X = a, Y = b ;

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-100 R O O T S

...

Finding Paths (4)a b c

d e f

Question: Is there a path from room X to room Y?

d e f

2. Attempt: Avoid looping through cycles in data by “remembering”connected(X Y) :- door(X Y)

path(X, Y) :- path(X, Y, [X]). // don‘t visit start node again

connected(X, Y) :- door(X, Y).connected(X, Y) :- door(Y, X).

path(X, Y, _Visited) :- connected(X, Y), not( element(Y, Visited) ).

path(X Y Visited) : connected(X Z)path(X, Y, Visited) :- connected(X, Z), not( element(Z, Visited) ),path(Z, Y, [Z|Visited]).

Remember each visited room in additional list parameterNever visit the same node twice

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-101 R O O T S

Finding Paths (5)a b c

d e f

Question: Is there a path from room X to room Y?

d e f

2. Attempt: Avoid looping through cycles in data by “remembering”connected(X Y) :- door(X Y)

path(X, Y) :- assert(visited(Z)), // don‘t visit start node againth (X Y)

connected(X, Y) :- door(X, Y).connected(X, Y) :- door(Y, X).

path__(X, Y).

path__(X, Y) :- connected(X, Y), not( visited(Y) )not( visited(Y) ).

path__(X, Y) :- connected(X, Z), not( visited(Z) ),assert( visited(Z) )

Constant time check

Remember visited rooms in dynamically created facts

assert( visited(Z) )path(Z, Y). ‘assert’ adds a clause

at run-time

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-102 R O O T S

y yNever visit the same node twice

Keep in Mind

Prolog predicates will loop infinitely ifth i t hi i l b f ithere is no matching non-recursive clause before a recursive onethere is no non-recursive “guard” literal before a recursive invocationthere are cycles in the data traversed by a recursive definitionthere are cycles in the data traversed by a recursive definition

either cycles in the data itselfor cycles introduced by rules

there is divergent construction of termsWe’ll see examples of this in the following section about lists!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-103 R O O T S

Chapter 2: Syntax and Semantics

A Short Diversion into Prolog Lists

R O O T S

Lists in Prolog

Prolog lists may be heterogeneous: They may contain elements of different types“different „types

Example: Homogeneous listsp g

[1, 2, 3] List of integers['a', 'b', 'c'] List of characters[ ] Empty list

E l H l t th t l l

[ ] Empty list[[1,2], [ ], [5]] List of lists

Example: Homogeneous only at the top level

[[1,2], [ ], ['a']] List of lists but the element types differ

Example: Fully heterogeneous

[[1 2] 'a' 3]

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-105 R O O T S

[[1,2], a , 3]

List are Binary Trees Encoded as Terms (1) (1)

Internally, lists are binary trees whose leaves are the lists elements:

.

[1, 2, 3].

1=.

2

3 []

Each list is terminated by an empty list

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-106 R O O T S

List are Binary Trees Encoded as Terms (2) (2)

The functor '.' is the list constructor: ?- .(1,[2,3]) = [1, 2, 3]

.

Tail.

1HeadTail

.2

Th fi t l t i th h d“ th d i th t il“

3 []

The first element is the „head“ the second is the „tail“. The „tail“ is the list of all the other elements.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-107 R O O T S

Accessing Head and Tail

Notation [ Head | Tail ]

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

?- [1 2 3 4]=[H1 H2|T]

H=1, T=[2,3,4]

H1 1 H2 2 T [3 4]?- [1,2,3,4]=[H1,H2|T].

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

H1=1, H2=2, T=[3,4]

H=3

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

?- []=[H|T].

???

???

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

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

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

X=[1,2,3,4], Y=1

???

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-108 R O O T S

? T [2,3,4], X [1|T].

Length of a List

Usually predefined://*** The predicate length(List, Int) suceeds iff Arg2 is* the number of elements in the list Arg1.*//length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.

Head Tail

Tracing an invocation of 'length' with input on first argument:?- length([1,2],N).

Call length([2],N1)g ,Call length([],N2) Exit lenght([],0)Creep N2 = 0C N1 i N2+1

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-109 R O O T S

Creep N1 is N2+1Creep N is N1+1

N=2

Length of a List

Usually predefined://*** The predicate length(List, Int) suceeds iff Arg2 is* the number of elements in the list Arg1.*//length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.

Head Tail

Tracing an invocation of 'length' without input on first argument:?- length(X,N).

Exit lenght([],0)g ,X=[], N=0 ;

Call length(X1,N1) Exit lenght([],0)C N1 0

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-110 R O O T S

Creep N1 = 0Creep N is N1+1

X=[G100], N=1 ;... produces infinitely many results ...

Concatenating Lists

Predicate definition/*** The predicate append(L1, L2, L12) suceeds iff Arg3 is* the list that results from concatenating Arg2 and Arg1.*/

append([], L, L).append([H|T], L, [H|TL]) :- append(T, L, TL).

Execution trace?- append([a, b], [c, d], L).

-> append([b] [c d] TL1])σ1 = {L ← [a|TL1]}

1 2-> append([b], [c, d], TL1]).-> append([], [c, d], TL2).-> □

σ2 = {TL1 ← [b|TL2]}σ3 = {TL2 ← [c, d]}

The result is the composed substitution σ1σ2σ3 = σ3(σ2(σ1))) restricted to the bindings for L:

L = [a| [b| [c, d]]] = [a, b, c, d]

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-111 R O O T S

Testing List Membership (1)

Predicate definition:/*** The predicate member(Elem, List) suceeds iff Arg1 is an element* of the list Arg2 or unifiable with an element of Arg2.*/

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

Execution trace?- member(2,[12, 2, 2, 3]).

C ll b (2 [2 2 3])Call member(2, [2, 2, 3]).Exit member(2, [2, 2, 3]).Redo member(2, [2, 2, 3]).Call member(2, [2, 3]).E it member(2 [2 3])

backtracking inititated by entering ;

Exit member(2, [2, 3]).Redo member(2, [2 ,3]).Call member(2, [3]).Call member(2, []).Fail

backtracking inititated by entering ;

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-112 R O O T S

Fail

Testing List Membership (2)

The member/2 predicate can be used in many differen “input modes”:

?- member(a, [a,b,c,d]). Is a an element of [a,b,c,d]?

?- member(X, [a,b,c,d]). Which elements does [a,b,c,d] have?

?- member(a, Liste). Which lists contain the element a?

?- member(X, Liste). Which lists contain the variable X?

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-113 R O O T S

Accessing List Elements

First element of a list first([X|_],X).

Last element of a list: last([X],X).last([ |Xs] X) :- last(Xs X)

N-th element of a list:

last([_|Xs],X) : last(Xs,X).

nth(1 [X| ] X)nth(1,[X|_],X).nth(N,[_|Xs],X) :- N1 is N-1, nth(N1,Xs,X).

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-114 R O O T S

Doing Something with all Elements

Sum of list elements: sum([],0).([H| T] S) (T ST) S i ST+H

Normal Execution:

sum([H| T], S) :- sum(T, ST), S is ST+H.

?- sum([12, 4], X). Call sum([4], ST])Call sum([],ST1)Exit sum([],0)Exit ST is 4+0=4Exit X is 12+ST=16

Goals with illegal modes or type errors:?- sum(X,3).ERROR: is/2: Arguments are not sufficiently instantiated

?- sum(X,Y).X = []X = [],Y = 0 ;ERROR: is/2: Arguments are not sufficiently instantiated

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-115 R O O T S

?- sum([1,2,a],Res).ERROR: is/2: Arithmetic: `a/0' is not a function

Chapter 2: Syntax and Semantics

Documenting Predicate Definitions

Difference of relations and functionsHow to document relations other than functions?How to document predicates that have different “input modes”?

R O O T S

Relations versus Functions (1)

In the functional programming language Haskell the following definition of the isFatherOf relation is illegal:of the isFatherOf relation is illegal:

isFatherOf x | x==frank = peterisFatherOf x | x==peter = paulisFatherOf x | x==peter = hans

x | otherwise = dummy

In a functional language relations must be modeled as booleanfunctions:functions:

isFatherOf x y| x==frank y==peter = Truei th Of | t lisFatherOf x y| x==peter y==paul = TrueisFatherOf x y| x==peter y==hans = True

x y| otherwise = False

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-117 R O O T S

Relations versus Functions (2)

Function application in Haskell must not contain any variables!O l th f ll i “ h k ” l lOnly the following “checks” are legal:

isFatherOf frank peterisFatherOf frank peter

True

False

In Prolog each argument of a goal may be a variable!So each predicate can be used / queried in many different input modes:p q y p

?- isFatherOf(kurt,peter).

?- isFatherOf(kurt,X).

Yes

Yes( , )

?- isFatherOf(paul,Y).

X = paul;X = hans

No

?- isFatherOf(X,Y). YesX = frank, Y = peter;X = peter, Y= paul;X = peter Y=hans;

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-118 R O O T S

X = peter, Y=hans;No

Relations versus Functions (3)

Haskell is based on functionsL th f li t i H k llLength of a list in Haskell

length([ ]) = 0length(x:xs) = length(xs) + 1

Prolog is based on relations

g ( ) g ( )

Length of a list in Prolog:length([ ], 0).length([X|Xs],N) :- length(Xs,M), N is M+1.g ([ | ], ) g ( , ),

?- length([1,2,a],Length). List with 3 arbitraryLength = 3

?- length(List,3).List = [ G330 G331 G332]

List with 3 arbitrary(variable) elements

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-119 R O O T S

List = [_G330, _G331, _G332]

Documenting Predicates Properly

Predicates are more general than functionsTh i t i lt b t d di th i tThere is not one unique result but many, depending on the input

So resist temptation to document predicates as if they were functions!p p yDon’t write this:

/*** The predicate length(List Int) returns in Arg2* The predicate length(List, Int) returns in Arg2 * the number of elements in the list Arg1.*/

Better write this instead:

/*** The predicate length(List Int) succeeds iff Arg2 is* The predicate length(List, Int) succeeds iff Arg2 is* the number of elements in the list Arg1.*/

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-120 R O O T S

Documenting Invocation Modes

Documenting the behaviour of a predicate thoroughly, including behaviour of special “invocation modes”:behaviour of special invocation modes :

“–” means “always a free variable at invocation time”“+” means “not a free variable at invocation time”

Note: This is weaker than “ground at invocation time”“?” means “don’t care whether free or not at invocation time”

//*** length(+List, ?Int) is deterministic* length(-List, -Int) has infinite success set** The predicate length(List, Int) succeeds iff Arg2 is* the number of elements in the list Arg1.*/length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-121 R O O T S

Chapter 2: Syntax and Semantics

Semantics (cont.): Negation

OK, we’ve seen how to prove or conclude what is true. But what about negation?

Closed world assumptionNegation as failure

“Unsafe negation” versus existential variables

R O O T S

Closed World Assumption

We cannot prove that something is false. W l h th t t it tWe can only show that we cannot prove its contrary.

isFatherOf(kurt,peter).

?- isFatherOf(adam,cain).no. means: we cannot prove that “isFatherOf(adam,cain)” is true

If we assume that everything that is true is entailed by the program, we may then conclude that what is not entailed / provable is not true.This assumption is known as the “Closed World assumption” (CWA)The conclusion is known as “Negation by Failure” (NF)

?- not( isFatherOf(adam,cain) ).yes.

means: we conclude that “not(isFatherOf(adam,cain) )” is true because wecannot prove that “isFatherOf(adam cain)” is true

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-123 R O O T S

cannot prove that isFatherOf(adam,cain) is true

Negation with Unbound Variables (1)

Prolog Deductive Databases

isFatherOf(kurt,peter).

?- isFatherOf(adam,X).

isFatherOf(kurt,peter).

?- ∀X.isFatherOf(adam,X).∃( , )no.

?- not( isFatherOf(kurt,X) ).no substitution for X returned!

( , )no.

?- ∀X.not(isFatherOf(adam,X)).unsafe infinite result set!

Deductive databases consider all variables to be universally quantified.

yes. no substitution for X returned! unsafe, infinite result set!

However, the set of values for X for which isFatherOf/2 fails is infiniteand unknown because it consists of everything that is not represented in the programin the program. So it is impossible to list all these values!Therefore, the above negated query with universal quantification is

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-124 R O O T S

, g q y qunsafe.

Negation with Unbound Variables (2)

Prolog Prolog (behind the scenes)

isFatherOf(kurt,peter).

?- isFatherOf(adam,X).

isFatherOf(kurt,peter).

?- ∀X.isFatherOf(adam,X).∃( , )no.

?- not( isFatherOf(kurt,X) ).no substitution for X returned!

( , )no.

?- ∃X.not(isFatherOf(adam,X)).safe

Prolog treats free variables in negated goals as existentially quantified.

yes. no substitution for X returned! yes. safe

So it does not need to list all possible values of X, just show that there is some value for which it fails, by showing that it does not succeed for

lany value

That is precisely what negation by failure does!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-125 R O O T S

That is precisely what negation by failure does!

Negation with Unbound Variables (3)

Existential variables can also occur in clause bodies:Th lThe clausemeans ∃X.∃Y. not(married(X,Y)) → single(X).

single(X,Y) :- not(married(X,Y)).

Take care: Prolog lets you write the following:The clause single(X,Y) :- not(married(X,Y)), sings(Y).

is the same assince it means

single(X,Y1) :- not(married(X,Y)), sings(Y1).

∃X.∃Y. ∀Y1(not(married(X,Y)) ∧ sings(Y1) ) →single(X)

Take care: The following is different from the above:

single(X).

Take care: The following is different from the above:The clausemeans

single(X) :- sings(Y), not(married(X,Y)).

∃X.∀Y. sings(Y) ∧ not(married(X,Y)) →i l (X)

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-126 R O O T S

single(X).

A Test

Predict what this program does!

f(1,a).f(2,b).f(2,c).

negation(X) :-not(

( f(X,c), output(X) :-format('Found f(~a,c) ', [X]).

f(4,c).

q(1).q(2).

output(X), g(X) )

),

output(X) :-format('but no g(~a)~n', [X]).

q(2).q(3).

), q(X).

?- negation(X).Found f(2,c) but no g(2)Found f(4,c) but no g(4)X=1 ;X=2 ;X=3 ;fail

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-127 R O O T S

fail.

Eliminate accidentally equal names!

nestedneg1(Y) :- % INST

q(Y), % -

not( ( p(X,Y), % -+

nestedneg1(Y) :- % INST

q(Y), % -

not( ( p(X,Y), % -+

not( ( f(X,Z), % +-

g(Z) % +

)

not( ( f(X,Z), % +-

g(Z) % +

)

),

q(Z) % -

)

),

q(Z1) % -

)

),

q(X) . % -

),

q(X1) . % -

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-128 R O O T S

Chapter 2: Syntax and Semantics

Disjunction

R O O T S

Didn’t you miss something?

We did not say how to translate “;” (disjunction) !

It is the same as two clauses, even if inlined

disjunction1(X,Y) :-

( q(X),p(X,Y), q(Z)) ; % --> (1,a), (2,b), (2,c)

( g(Y),f(X,Z)) . % --> (1,11), (11,2), ...

disjunction1(X,Y) :-

q(X),p(X,Y), q(Z)). % --> (1,a), (2,b), (2,c)

disjunction1(X,Y) :-

g(Y),f(X,Z)) . % --> (1,11), (11,2), ...

Therefore, variables with the same name in different disjunct branches are different variables!

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-130 R O O T S

are different variables!

Didn’t you miss something?

We did not say how to translate “;” (disjunction) !

It is the same as two clauses, even if inlined

disjunction2(X,Y) :-

( X=A1, Y=B1, Z=C1, q(A1),p(A1,B1), q(C1)) ; % --> (1,a), (2,b), (2,c)

( X=A2, Y=B2, Z=C2, g(B2),f(A2,C2)) . % --> (1,11), (11,2), ...

disjunction1(A1,B1) :-

q(A1),p(A1,B1), q(C1). % --> (1,a), (2,b), (2,c)

disjunction1(A2,B2) :-

g(B2),f(A2,C2) . % --> (1,11), (11,2), ...

Variable renaming and explicit unification in each branch makes visible what’s going on behind the scenes…

© 2009 Dr. G. Kniesel Course „Advanced Logic Progrmming“ (ALP) Page 2-131 R O O T S

what s going on behind the scenes…

Chapter Summary

Prolog SyntaxP l lit l

Declarative / Model-based SemanticsPrograms, clauses, literals

Terms, variables, constants

Semantics Herbrand UniverseHerbrand Interpretation

Semantics: BasicsTranslation to logic

Herbrand Model

Negation as FailureOperational / Proof-theoretic Semantics

U ifi ti SLD R l ti

Negation as FailureClosed World AssumptionExistential Variables

Unification, SLD-ResolutionIncompleteness because of non-termination

DisjunctionEquivalence to clauses

Dealing with non-terminating programs:

Order of literals / clauses

qVariable renaming

shrinking termsloop detection