Logic programming and Prolog - Lecture Notes | ECS 140A, Assignments of Programming Languages

Material Type: Assignment; Class: Programming Languages; Subject: Engineering Computer Science; University: University of California - Davis; Term: Unknown 1989;

Typology: Assignments

Pre 2010

Uploaded on 07/30/2009

koofers-user-8zr-1
koofers-user-8zr-1 🇺🇸

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Logic Programming and Prolog
Motivation
Functional Programming involves programming with
functions. Substitute a function with its body. Also given a set
of input, get an output
(left right)
Logic programming involves programming with relations,
where a relation is a set of tuple. n-ary relation: set of
n-tuples
Substitution can work either way in a relation.
(left right)
Example: append a ternary relation on lists:
hx, y, zi append
h[],[],[]i append
h[6],[7,8],[6,7,8]i append
h[6,7],[8],[6,7,8]i append
h[7,8],[6],[6,7,8]i 6∈ append
h[6,7,8],[6],[7,8]i 6∈ append
Logic programming involves three elements:
1. Terms that represent entities and relationships among
entities
2. facts and rules that specify relationships among terms,
and
3. queries that ask questions about how terms are related
with respect to a collection of facts and rules.
ECS140A, Winter’06Logic Programming, slide 1 c
Raju Pandey
Prolog
Terms
Facts, rules, and queries are specified using terms.
Simple term:
1. Atoms: symbolic atoms refer to specific objects.
Example: append, parent, x, y, z
2. Number: 1, 3, 4, 4.8
3. Variable: A variable can stand for other values. Variables
must begin with an uppercase, or the underscore ( ).
Example: X, Variable, Y, Z, aVar
Compound term: Atom followed by a parenthesized
sequence of sub-terms. Atom is called functor and
sub-terms are called arguments.
Example:
link(bcpl, c)
link: functor. Note that link is not a function.
bcpl, c: arguments.
Compound terms can be nested:
tree(a, tree(b, nil, nil),
tree(c, tree(d, nil, nil),
tree(e, nil, nil)
)
)
What this term may mean in real world:
a
cb
d e
tree(a,
tree(b, nil, nil),
tree(c,tree(d, nil, nil),
tree(e, nil, nil)
))
ECS140A, Winter’06Logic Programming, slide 2 c
Raju Pandey
Facts
Facts: A fact expresses unconditional relationship among
terms.
Assume the following relationships among various
languages:
Algol60
Fortran
Simula67
CPL
BCPL
C
C++
SmallTalk
Represent the relationship between two languages through
term link: let link(x, y) mean that language y is derived from x.
A set of facts that represent the above graph:
link(fortran,algol60).
link(algol60,cpl).
link(cpl,bcpl).
link(bcpl,c).
link(c,cplusplus).
link(algol60,simula67).
link(simula67,cplusplus).
link(simula67,smalltalk80).
link(bcpl, c) specifies that cis a derivative of
bcpl.
ECS140A, Winter’06Logic Programming, slide 3 c
Raju Pandey
Rules
Similar to facts, except that they assert a truth of a relation
that is guaranteed only under cer tain conditions.
Logically connects a collection of relations in a conditional
form:
How rules are written
concl :- cond1,
cond2,
.
.
.
condN
What they mean
concl is true
if cond1 is true and
if cond2 is true and
.
.
.
if condN is true
Example:
xgrandfather z :- x father y,
y father z.
x grandfather z :- x father y,
y mother z.
Rule also called a clause with a head and a body
Head: x gradfather z
body: x father y, y father z
General rules have the following form:
Pif (Q1and Q2and ... and Qk), where k0
Informal semantics: Pis true if Q1and Q2,..., and Qkare
true. Formally:
P(Q1Q2... Qk)
ECS140A, Winter’06Logic Programming, slide 4 c
Raju Pandey
pf3
pf4
pf5

Partial preview of the text

Download Logic programming and Prolog - Lecture Notes | ECS 140A and more Assignments Programming Languages in PDF only on Docsity!

Logic Programming and Prolog

Motivation

• Functional Programming involves programming with

functions. Substitute a function with its body. Also given a set of input, get an output

(left → right)

• Logic programming involves programming with relations,

where a relation is a set of tuple. n-ary relation: set of n-tuples

• Substitution can work either way in a relation.

(left ↔ right)

• Example: append — a ternary relation on lists:

〈x, y, z〉 ∈ append

〈[], [], []〉 ∈ append 〈[6], [7, 8], [6, 7 , 8]〉 ∈ append 〈[6, 7], [8], [6, 7 , 8]〉 ∈ append 〈[7, 8], [6], [6, 7 , 8]〉 6 ∈ append 〈[6, 7 , 8], [6], [7, 8]〉 6 ∈ append

• Logic programming involves three elements:

  1. Terms that represent entities and relationships among entities
  2. facts and rules that specify relationships among terms, and
  3. queries that ask questions about how terms are related with respect to a collection of facts and rules.

ECS140A, Winter’06 Logic Programming, slide 1 ©c Raju Pandey

Prolog

Terms

• Facts, rules, and queries are specified using terms.

• Simple term:

  1. Atoms: symbolic atoms refer to specific objects.

Example: append, parent, x, y, z

  1. Number: 1, 3, 4, 4.
  2. Variable: A variable can stand for other values. Variables must begin with an uppercase , or the underscore ( ).

Example: X, Variable, Y, Z, aVar

• Compound term: Atom followed by a parenthesized

sequence of sub-terms. Atom is called functor and sub-terms are called arguments.

- Example: link(bcpl, c)

link: functor. Note that link is not a function.

bcpl, c: arguments.

- Compound terms can be nested: tree(a, tree(b, nil, nil), tree(c, tree(d, nil, nil), tree(e, nil, nil) ) ) What this term may mean in real world: a

b c

d e

tree(a, tree(b, nil, nil), tree(c, tree(d, nil, nil), tree(e, nil, nil) ) )

ECS140A, Winter’06 Logic Programming, slide 2 ©c Raju Pandey

Facts

• Facts: A fact expresses unconditional relationship among

terms.

• Assume the following relationships among various

languages:

Algol

Fortran

Simula

CPL

BCPL

C

C++

SmallTalk

• Represent the relationship between two languages through

term link: let link(x, y) mean that language y is derived from x.

• A set of facts that represent the above graph:

link(fortran,algol60). link(algol60,cpl). link(cpl,bcpl). link(bcpl,c). link(c,cplusplus). link(algol60,simula67). link(simula67,cplusplus). link(simula67,smalltalk80).

• link(bcpl, c) specifies that c is a derivative of

bcpl.

Rules

• Similar to facts, except that they assert a truth of a relation

that is guaranteed only under certain conditions.

Logically connects a collection of relations in a conditional form: How rules are written concl :- cond1, cond2, .. . condN

What they mean concl is true if cond1 is true and if cond2 is true and .. . if condN is true

• Example:

x grandfather z :- x father y, y father z. x grandfather z :- x father y, y mother z.

• Rule also called a clause with a head and a body

Head: x gradfather z

body: x father y, y father z

• General rules have the following form:

P if (Q 1 and Q 2 and ... and Qk ), where k ≥ 0

Informal semantics: P is true if Q 1 and Q 2 ,..., and Qk are

true. Formally:

P ⇐ (Q 1 ∧ Q 2 ∧ ... ∧ Qk)

Queries

• A functional program is defined by a set of functions. Its

execution is driven by evaluation of expressions. A logic program, on the other hand, is defined as a set of rules ; its execution answers a certain query.

• Given the database of relationships, query the database

regarding the existence of certain relationships.

• A query has the following form: t 1 , t 2 , t 3 · · · tk.

Formal semantics: t 1 ∧ t 2 ∧ ...tk

Informally: can we prove that t 1 , t 2 , ..., and tk are true from

the database of facts?

• Queries are also called goals and individual terms subgoals.

• The prolog runtime system will use the database of facts to

deduce a goal. If it is successful, it will return yes , otherwise no.

Yes ⇒ Prolog can deduce some fact No ⇒ a failure to

deduce a fact. Rules cannot be used to deduce negative facts.

• Simple queries:

?- link(c, cplusplus). yes

?- link(algol60, simula67), link(bcpl, c). yes

?- link(c, bcpl), link(bcpl, c). no

ECS140A, Winter’06 Logic Programming, slide 5 ©c Raju Pandey

Relations containing variables

• Recall: predicate x grandfather y used to signify that

x is grandfather of y.

Not a very succinct way of representing facts; will need to enumerate all such facts one by one. Quite tedious.

• What we need is some way to define relationships among

generic terms, that is terms that can stand for other terms.

• Variables achieve those.

gradfather(X, Z) :- father(X, Y), father (Y, Z). gradfather(X, Z) :- father(X, Y), mother (Y, Z).

Here, X, Y, and Z can take any value.

• Important points:

  • All occurrences of same variable name within a single statement denote the same variable.
  • A fact containing variables asserts that all instances of the fact that result from consistently instantiating all variables are true.

• Example instantiations of variables and their meaning:

grandfather(bill, mary) :- father(bill, Y), father(Y, mary). grandfather(bill, Z) :- father(bill, Y), mother(Y, Z). grandfather(john, jim) :- father(john, bob), father(bob, jim).

• Anonymous variables( ): A variable that takes matches

anything, but never takes any value. Example: check if bill has a father. We don’t care who the father is. ?- father(bill, _).

ECS140A, Winter’06 Logic Programming, slide 6 ©c Raju Pandey

Unification

• Logic programming’s fundamental operation: How does

Prolog bind variables to values?

Unification is an attempt (by Prolog interpreter) to match two terms, by instantiating the variables contained in two terms.

• Example: When do two terms f(X, b) and f(a, Y)

match?

For X=a, and Y=b, the two terms are equal.

So unification will involve assigning these values to the variables.

Term f(a, b) is called an instance of f(X, b).

• Two terms t1 and t2 unify if they have a common instance

U.

• Where does unification take place?

  1. when two terms are checked if they are equal, through the equality operator f(X, a) = f(b, Y)
  2. Unification occurs implicitly when a rule is applied: identity(Z, Z). ?- identity(f(X, b), f(a, Y)). X = a Y = b Note each occurrence of a given variable gets the same instantiation. g(a, a) ∈ g(X, X) g(f(a, b), f(a, b)) ∈ g(X, X) g(a, b) 6 ∈ g(X, X)

Queries

• Queries with variables:

Algol

Fortran

Simula

CPL

BCPL

C

C++

SmallTalk

?- link(cpl, X). X = bcpl; no means set of all X such that <cpl, X> ∈ link

?- link(X, cplusplus). X = C; X = simula67; means set of all X such that <X, cplusplus> ∈ link

?- link(X, smalltalk80), link(X, cpluscplus). X = simula67. means set of all X such that <X, smalltalk80> ∈ link ∧ <X, cpluscplus> ∈ link

?- link(algol60, X), link(X, Y). X = cpl Y = bcpl;

X = simula Y = cplusplus;

X = simula Y = smalltalk80; no

Arithmetic in Prolog

• Prolog defines usual +, -, *, etc operators for performing

arithmetic. Use infix notation for specifying expressions.

• An expression is like any other term

• They are not evaluated unless explicitly asked to. Unification

rules apply on them as well: ?- X = 2 + 3. X = 2 + 3

Binds X to term 2 + 3.

• In order to evaluate an expression, use is:

?- X is 2 + 3. X = 5

• Check the following:

?-X is 2+3, X = 2 + 3. no

term 2+3 does not unify with term 5

• Example 1:

sum(1, 1). sum(N, Res) :- N > 1, N1 is N - 1, sum(N1, Res1), Res is Res1 + N.

?- sum(5, X). X = 15

• Example 2: close_enough succeeds if two numbers are

equal to within 0.0001. close_enough(X, X) :-. close_enough(X, Y) :- X < Y, Y-X < 0.0001. close_enough(X, Y) :- X > Y, close_enough(Y, X).

ECS140A, Winter’06Logic Programming, slide 13 ©c Raju Pandey

Logical operators

• true: goal always succeeds

• fail: always fails

• Equality (=): A term X = Y succeeds if X and Y match.

Prolog will try to match them: ?- X = 5. X = 5.

• Inequality(=): = is opposite of =

• Negation: The term not(X) succeeds if an attempt to

satisfy X fails.

?- X = 2, not(X = 1). X = 2.

Unify X with 2 first, and use that X to check if X = 1. ?- not (X = 1), X = 2. no

(X = 1) succeeds by unifying X with 1. Negation term

fails causing the whole clause to fail.

• X ; Y: specifies disjunction (or) of goals. The goal succeeds if

X succeeds or Y succeeds. Fails when both fail. person(X) :- (X = adam; X=eve; mother(X, Y)).

ECS140A, Winter’06Logic Programming, slide 14 ©c Raju Pandey

Control in Prolog

• A prolog program contains

  • A sequence of clauses (forming the data base), and

– a query of the form A:- B 1 , B 2 ,... , Bn.

• Program evaluation strategy: characterized by two decisions:

– Goal order: Subgoals are processed left → right

– Rule order: Rules are applied top → bottom.

Response to a query is affected both by goal order within the query and by rule order within database of facts and rules

• Algorithm for control:

Start with a query as the current goal; while the current goal is nonempty do let the current goal = G 1 , ..., Gk , where k ≥ 1 choose the leftmost goal G 1 ; if a rule applies to G 1 then select first such rule A :- B 1 , ..., Bj , where j ≥ 0 let σ be most general unifier of A and B 1 current goal = B 1 σ, B 2 σ, ...Bj σ, G 2 σ, ..., Gk σ else backtrack; end while success

Example

• Example: Let rules be

append([], Y, Y). append([H|X], Y, [H|Z]) :- append(X, Y, Z).

prefix(X, Z) :- append(X, Y, Z).

suffix(Y, Z) :- append(X, Y, Z).

sublist1(S, L):- prefix(X, L), suffix(S, X). sublist2(S, L):- suffix(S, X), prefix(X, L).

X S Z

How does search take place?

• Example query:

?- suffix([a], L), prefix(L, [a,b,c]). L = [a].

• Search tree with no backtracking:

{_1−>[], L−>[a]} append([], [a], [a]).

{_2−>[b,c]} append([],[b,c],[b,c]).

suffix([a], L), prefix(L, [a, b, c])

append([a],_2, [a,b,c])

prefix([a], [a,b,c])

append([], _2, [b, c])

append(_1, [a], L), prefix(L, [a, b, c])

yes

prefix([a],[a,b,c]) if append([a],_2, [a,b,c]).

suffix([a], L) if append(_1, [a], L).

append([a],_2,[a,b,c]) if append([],_2,[b,c]).

ECS140A, Winter’06Logic Programming, slide 17 ©c Raju Pandey

How does search take place?

• Example query:

?- suffix([b], L), prefix(L, [a,b,c]). L = [a, b].

• Search tree with backtracking:

{_1−>[], L−>[b]}

{_1−>[_3|_4], L−>[_3|_5]}

{_3−>a}

{_6−>[c]}

...

suffix([b], L), prefix(L, [a, b, c])

append(_1, [b], L), prefix(L, [a, b, c])

prefix([b], [a,b,c])

append([b],_2, [a,b,c])

backtrack

append(_4, [b], _5), prefix([_3|_5], [a, b, c])

prefix([_3,b], [a,b,c])

append([_3,b],_6, [a,b,c])

append([b],_6, [a,b,c])

append([],_6, [c])

Yes

ECS140A, Winter’06Logic Programming, slide 18 ©c Raju Pandey

Does goal order matter?

• Order of subgoals within a query affects prolog search tree

?- suffix([a], L), prefix(L, [a, b, c]). L = a ; [ infinite computation ]

• Why? The leftmost subgoal

?- suffix([a], L). L = a ; L = [_1, a] ; L = [_1, _2, a] ; ...

has an infinite number of solutions, only the first of which

satisfies prefix(L, [a, b, c]).

The system first finds a solution without backtracking. A futile search through the rest of infinite tree ensues if we ask for a further solution.

• what about reordered query?

?- prefix(L, [a, b, c]), suffix([a], L). L = a ; no

This query has a finite prolog search tree.

Does rule order matter?

• Yes they do since rule orders change the order in which

solutions are searched. app2([H|X], Y, [H|Z]) :- app2(X, Y, Z). app2([], Y, Y).

?- appen2(X, [c], Z).

• Search tree:

{X−>[], Z−>[c]}

yes

yes

yes

X=[], Z=[c]

X=[_1], Z=[_1,c]

appen2(X, [c], Z)

{X−>[_1|_2], Z−>[_1|_3]} {X−>[], Z−>[c]}

...

appen2(_2, [c], _3)

append(X, [c], Z)

{X−>[_1|_2], Z−>[_1|_3]}

yes

{_2−>[], _3−>[c]}

X=[_1], Z=[_1,c] (^) ...

X=[], Z=[c] append(_2, [c], _3)

{_2−>[], _3−>[c]}