Você está na página 1de 10

2008-09-18

Crash Course in Prolog Introduction to PROLOG


Peter Funk PROgramming in LOGic
(preliminary version)
 Prolog-program are declarative and
consist of properties, relations and rules.
 Lisp and Prolog are the most common
programming languages for symbolic AI.
 Good to ”explore” and ”prototype
programming".
 Prolog are based on Horn-clauses, a
subset of first order predicate logic.

Important to know about Prolog Traditional Programming


 Basics in Prolog:
facts, lists [], meta-logical predicates, Imperative programming:
accumulator, tail-recursion, (DCG),  An abstraction of the Turing machine (a

generate-and-test, search. program is instructions to a Turing


 Connection to other areas: Relational machine).
data-baser, Expert systems, Formal and  Have an ”operational semantic” in terms

automata-theory, (Natural language of what the Turing machine has to


processing). perform.
 To think declarative.  Is context dependent (what operations
have been made before).

Logic programs Logic and Programming


A logic has 4 parts
 A description in a suitable logical notation · syntax (describing logical formulas)
describing a part of a world or a fictive · semantic (exact meaning)
world. · a number of axioms (e.g. Tautologies: [a]
= [a|[]] }
· inference rules (e.g. modus ponens, “if a
 Description of everything needed to solve so b”)
a task:
->relations between objects in a world Logics: propositional logic, first order logic,
(people, numbers, lists, trees, …). predicate logic, typed logic, temporal logic
(events, intervals, …), modal logic (probability,
maybe, true in all worlds,…)

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 1
2008-09-18

Prolog & Logic today: Status today for Logic and Logic
 Prolog is used for prototypes
programming:
 Some larger commercial systems (links to .exe and formal verification of safety critical systems
users often not aware that system is in Prolog). (landnings wheels in air plains, train
 Compilation and Interpretation systems (Erlang used signals, medical hardware, etc).
at Ericsson is initially written in Prolog).
 Graphic packets, fast execution, good interfaces to
Hardware design (TTL-logic circuit,
other programming languages (calls to/from e.g.
C++/Java).
true=1=5 volt, false=0=0 volt), predicate
logic, temporal logic, modal logic
 Used in natural language processing, interpretation,
translation etc.
 Good interfaces to web applications, web pages can
use prolog (exv. LPA-Prolog – html – php - mySQL).

Declarative description ~ Imperative


Future for Prolog? Example for declarative description
 Knowledge representation (SDL, XML, Find all grand children of a certain person X.
Relation databases -> Knowledge bases, Declarative description
natural language), temporal logic. A grand child of X is a child of one of X’s children
Imperative description
 Safety critical systems need proof of their In order to find on grand child of X, first find one child of X, and
correctness then find a child of this child.
 Air plane, transportation, telecommunication, Imperative description II
To find a grand child of X, first find a parent of one child, then
medicine, etc (programs i C are very difficult to check if the parent is a child of X.
test !). read(person);
 Prolog is developed: for i := 1 to max_child do
if child[i,1] = person then
•Logic:
∀ X ∀ Y (∃
∃Z
 Constraint Logic Programming (CLP): for j := 1 to max_child do (child(X, Z) and child(Z, Y))
if child[j,1] = child[i,2] then → grandchild(X, Y)).
 parallel-execution writeln(child[j,2]);
 Agent programming fi Prolog:
od
 web programming fi grandchild (X,Y) :- child(X,Z), child(Z,Y).
od

Declarative and imperative


languages Different Language paradigms
Imperative language Declarative language
 imperative languages are concrete and
Philosophy Apply instructions of Apply descriptions of enforcing, i.e., a given execution order.
how to solve the
problem
what the problem is
”high level instructions to a processor”.
declarative program:
Program A sequence of A set of assertions
commands  Nothing about how it should be executed
(true in ”pure Prolog”).
Example Basic, C, C++, Ada, Prolog, ML, Scheme,
Java, Perl, Phyton, … Gödel, mercury, Oz,  Describe only the problem and the
(SQL), …
information of the problem.
Fast and specialized General, readable and  Origin in logic and how humans make
Strength
program possibility of correct
program
logical reasoning.

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 2
2008-09-18

Logic History
400 fK The first foundation was built by Aristoteles (axiom, premise, Some Important Notes (Logic)
conclusion “Alla valar är däggdjur" osv).
1930 Subject stabilized [Gödel, Church, Russel, etc.]. (Predicate logic
completely explored Church-Turing-sentence => predicate logic ==
calculable functions)  Predicate name is a name standing for both
1960 Automatic Theorem Proving & AI. property and relation.
1965 Resolution and unification [Robinson]. Resolution: an effective
conclusion drawing but rules must be written in a special form.  Predicate name is followed by arguments.
1972 The first Prolog-implementation [Colmerauer].
Arity gives the number of arguments of the
1974 Logic programming (SLD-resolution) [Kowalski] (Algoritm = logic +
control, let computers decide how the problem should be solved, i.e., predicate.
execution ord).  Arity= 0: propositional logic (no argument) SUNNY
1977 Negation (SLDNF-resolution) [Clark]. (SLDNF completed negative
assertion “A penguin can not fly").  Arity= 1: property man(peter)
1978 Edinburgh Prolog [Warren] (most common syntax today).  Arity= 2: relation lenght(peter,1.95)
1981 Japanese announce its 5:e-generation project: robotic, AI, etc, with
logic programming (”main result”: increased use of computers in  Arguments are called terms. A term can be
Japan with Kanji, romaji). constant, variable or a structure.
1995 – Constraint Logic Programming (CLP), Agent Programming (logic
bubbles), …

Del 2: Test Prolog Prolog is different


 Free Prolog for Education  Prolog has no global variables.
(Linux/Mac/Windows):
 No changing of variable values
http://www.swi-prolog.org/
 No iterative constructions (e. g. loop)
Only needs about 4 Meg.  No ”if … then” format
 Recursion is central in Prolog
Many Prolog introductions on web, search with
google : Prolog tutorial introduction

Concept in Prolog Property Written as


man(adam).
 True or false, a Prolog expression can only man(kalle).
accept two values, true or false man(lasse). % Complete always with a point.
 Two arguments can be equal or different. woman(lisa).
woman(eva).
Equality can be obtained by binding free
variables. RELATIONs written as:
 Search, Prolog is based on searching, Prolog parent(adam,peter). % adam is parent of peter
parent(eva,kalle).
tries to find a solution and test different parent(eva,lisa).
ways. parent(lisa,lasse).
 Backtracking, if search fails, Prolog goes back parent(kalle, knut). Rest text after % is
and tests alternative ways. comment

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 3
2008-09-18

Definition of Rule Prolog Interpretations


Every rule has a head – name which defines the  Facts and rules can be typed into the interpreater
relation. ending with ”.”
Every rule has a body – definition of the relation.  Facts and rules can be written in files ending with .pl
and loaded ["File-name.pl"].
Definitions of father and mother are as
follows:
Enquire Prolog if there are certain woman
”If M is a woman and M is parent of C then M is mother | ?- woman(X).
of C”:
mother(M,C):- woman(M), parent(M,C). Prolog Prompt: Prolog always
X = lisa ? ; write out”?-”. After prompt you type
”If F is a man and F is parent of C then F is father of C”: X = eva ? ; the question.
father(F,C):- man(F), parent(F,C). no
| ?- ”;” ask for more solutions
”,” means logic ”AND”, both (give alternative
”:-” means logic implikation, ←
man och parent must be true in
but this is not available on keyboard, solutions if available).
order for father to be true.
so prolog has adopted :-

Type one row of text finished with .pl ;


We only want to know if there exists any olive_oil(kanakis).
woman olive_oil(kalamata).
region(kanakis, greece).
region(kalamata), spain).
| ?- woman(_). quality(kanakis, vergine).
quality(kalamata, extra_vergine).
yes
Do we have whisky from Islay and if so how old?
| ?- child(_).
| ?- region(W, greece), quality (W, A).
no
A = vergine,
W = kanakis ? ;
W is bounded to
no
Prolog is based on ”negation as failure”, all | ?- greece
that is not known is false (little more
about this later).

olive_oil(primo_grande).
quality(primo_grande, extra_vergine). Structure
year(primo_grande, 2007).
acidity(primo_grande,high). 3 other ways to write the same thing:
acidity(primo_grande,spain).
color(primo_grande,dark_green). oil(primo_grande, 2007, high, vergine, spain, dark_green).

Do we have a extra vergine olive oil produced after oil(primo_grande, 2007, [acidity, high],[quality, vergin], [origin,
2006? spain], [color, dark_green).
| ?- olive_oil(O), quality(O, extra_vergine), year(O,Y), Y>2006.
oil(primo_grande, 2007, flavor(acidity(high), quality(vergin),
Y = 2007, origin(spain), color(dark_green))).
O = primo_grande ? ;
no
| ?- Warning: easy to misunderstand structure,
there is no function in Prolog!

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 4
2008-09-18

oil(primo_grande, 2007, flavor(acidity(high), oil(primo_grande, 2007, flavor(acidity(high), quality(vergin),


quality(vergin), origin(spain), color(dark_green))). origin(spain), color(dark_green))).

| ?- flavor(A, _, C). | ?- flavor(W, _, flavor(acidity(A), _,_)).

C = flavor(acidity(high), quality(vergin), A = high,


origin(spain), color(dark_green)), W = primo_grande ? ;
A = primo_grande ? ;
no
no | ?-
| ?-

olive_oil(primo_grande).
olive_oil( primo_grande).
More Rules man(peter
man( peter).).

olive_oil(primo_grande). likes(M, W) :-
:- man(M), olive_oil(W).
olive_oil(W).

quality(primo_grande, extra_vergine).
year(primo_grande, 2007). What does Peter like?
| ?- likes(peter, X).
human(peter). X = primo_grande? ;
no
% For any man M and O it is valid that …. | ?- \+ likes(peter, primo_grande).
% M likes O. No
| ?- \+ likes(lisa, primo_grande).
likes (M, O) :- human(M), olive_oil(O).
Yes
Negation, ”it is not true”, written as ”\+”

Task (assignment)
man(adam). man(kalle). man(lasse).
woman(lisa). woman(eva). woman(mia).
Idea to Solve Assignment)
parent(adam,lasse). % adam is parent of lasse
parent(eva,kalle). parent(eva,lisa). parent(lisa,lasse). cousin(K1, K2):-
parent(kalle,knut). Test i Prolog
parent(P1, K1),
?- cusin(X,Y).
cusin(X,Y).
parent(P2, K2),
father(F,C):- man(F), parent(F,C). X = lasse
siblings(P1,P2).
mother(M,C):- woman(M), parent(M,C).
Y = knut ;
1) Add the fact that kalle has one daughter mia. siblings(S1,S2):- no
parent(X,S1),
2) Draw a family tree.
parent(X,S2),
3) Write a rule to define relation cousin, e.g. find out
who mia’s cousin is. S1 \== S2. % S1 and S2 must not be the same person,
extra: 3a) write a rule to define grand mother. 3b) use % one can not be siblings of himself☺
that rule to show that eva is lasses grand mother.
Apply the relation mother with two arguments (to
show the arity of a predicate one usually write
mother/2).

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 5
2008-09-18

Lists
List
 [ ] : one empty list ?- [a,b,c] = [Head|Tail].
 [1, 2, abba] : a list containing 3 elements Head=a
Separate head and tail
Tail=[b,c]
 [[11, 12, 13], [21, 22, 23], [31, 32, 33]]
| ?- [a] = [H|T].
:a 3x3 matrix (a list which contains 3
H=a
lists which...).
T=[]
Head of list, tail of list.
These lists are identical
?- [a,b,c] = [a|[b,c]] = [a|[b|[c]]] = [a|[b|[c|[]]]].

Yes

Certain simple predicate:


member member
% Predicate member
% X is member of list if X appears the first in the list. member(X,L) :- L = [X|Rest].
member(X,L) :- L = [F|Rest], member(X, Rest).
member(X, [X|_]).
% otherwise X is in the resten of the list. | ?- member(X, [abba, 1, 3]).
member(X, [_|Rest]) :- member (X, Rest).
X = abba ? ;
| ?- member (1, [abba, 1, 3]). X=1?;
X=3?;
yes Tail_recursion with the
function calling itself. This is
same effective as loop no
written in C if one does not
care about the execution | ?-
time.

member first, second, tail


| ?- first(X, [kalle,lisa,mats]).
| ?- medlem(1, [A, B]). %The first element in list.
X = kalle? ;
first(X, [X|_]).
no
| ?-
A=1?; tricky, A and B are variables and can
% the second element i list. | ?- second(X, [kalle,lisa,mats]).
B=1?; take any values, for example, 1.
Hence, the first elementet in list can second(X, [ _,X|_ ]). X = lisa? ;
be ”1”, and the second element i list no
| ?-
no can also be ”1”. % Rest of list.
| ?- tail(X, [kalle,lisa,mats]).
| ?- tail(R, [ _|R]).
X = [lisa,mats]? ;
no
| ?-

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 6
2008-09-18

Arithmetic and others


 Which are true or false: <, >, >=, =<, =:=, | ?- 2 =< 4.
=\= (reduce right and left leden). yes
 is (example ?- X is 4 + 3)
 = (unification, Prolog attempts to bind all | ?- 2+2 =\= sin(0), 0 + 0 =:= sin(0).
unbounded variables as much as possible. If yes
this is succeeded then unification is done).
 Operator +, -, *, /, sin, cos, tan

Trace A is B.
| ? - trace, X is sin(4/5), X>2.
Expression B is calculated and unified with
1 1 Call: _59 is sin(4/5) ? <ENTER> variable (or constant) A.
1 1 Exit: 0.71735609 is sin(4/5) ? | ? - Area is 3.14 * 5 * 5.
<ENTER> Area = 78.5 ? <ENTER>
2 1 Call: 0.71735609 > 2 ? <ENTER> yes
| ? - 4 is 4.
2 1 Fail: 0.71735609 > 2 ? <ENTER> • As the right side of ”is” has
yes to be calculable, it must not
1 1 Redo: 0.71735609 is sin(4/5) ? contain unbounded variable.
| ? – X is 2 + M.
<ENTER>
ERROR
1 1 Fail: _59 is sin(4/5) ? <ENTER> | ? – M = 2, X is 2 + M.
”Redo” means that Prolog interpretor backtracks (backs one X=4
or more steps to find alternative solutions).

Strict equality”==” Unification ’=’


| ?- V == Q. % variable V is not strictly same as Q
Two predicates can be unified if
% one could instantialize V = 1 och Q till 2 if he/she will * they have the same name
no  They have the same amount of
| ?- V = 5, Q = 5, V == Q. % now are both strictly
equal (both =5). terms
yes  Their terms can be unified
| ?- 1+2 == 2+1. % structure 1+2 is not strictly equal
to 2 + 1 Two terms kan be unified if
no  One is a variable
| ?- 1+2 == 1+2.
 both are same constants
yes
 Both are structures...

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 7
2008-09-18

Example of unification -1
Unification ”=” continue | ?- xx(left, 123, X) = xx(A,B,B).
A = left,
two structures can be unified if B = 123,
X = 123 ? ;
 they have same constructor
(name) | ?- cbc = X.
X = cbc ?
 They have same arity
| ?- +(5,5) = 5 + 5
 Arguments can be unified yes

Failed example:

| ?- X = 5 + 5, X = 10.
no

Example of unification-2 Example of unification-3a


| ?- E = 1+2. % predicate lenght1
E = 1+2 ? <ENTER> length1(0, [ ]).
Yes (E is assigned with structure ”1+2”
length1(N, [ F|R]) :- length1(N2, R),
which is same as +(1,2)
N = N2+1.
| ?- p(p(p(p(0)))) = p(p(X)). | ?- length1(X, [a,b,c]).
X = p(p(0)) ? ; X = 1+(1+(1+0)) ? ;
no no
| ?- | ?-

Example of unification-3b Syntax


% predicate lenght1  Predicate: mamma, mMM, no_1_.
length1(0, [ ]).  Variables: W, W12, _12
length1(N, [ F|R]) :- length1(N2, R),  Constants: stefan, sTEFAN, ’Stefan’
N is N2+1.  Structures: node(node(X,10,nil),12,nil).
| ?- length1(X, [a,b,c]).  Lists: [], [1,2, [44, 55], 3], [a,n(1,2,3)]
X = 3;  Arithmetic & others: +, -, *, /, sin, cos,
tan, <, >, >=, =<, =:=, =\=, ==, =, is
no
 Figures and numbers: 0,…, 9, 123.31,
| ?-
55.2e-3

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 8
2008-09-18

Closed world assumption (CWA) Negation i Prolog


Example: SJ announces that every day one train goes
from Linköping to Stockholm at 9:22. But it is not
”Negation by failure” is written i prolog as ”\+”
explicitly stated that no train goes at 9:56 or 10:24.

Because a train at 9:56 is not indicated, we presume no


train goes at that time. Example:

CWA: All those which are not explicitly stated are not
true. ?- X = z, \+ member(X,[a,b,c]).
yes
Negation as Failure: ?- X = c, \+ member(X,[a,b,c]).
NF: Whatever Prolog program can not derive in finite
no
time is false.

SLD-tree for ← member(X, [a, b, c]).


How Prolog find all solutions Program: member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
 Depth-first search with s k backtracking:
 When a leaf node is encountered, the ← member(X, [a, b, c]).

interpreter goes back to the preceding


branch and test next alternatives. ← ← member(X, [b, c]).
X/a
 Problem: endless subtree ⇒ endless loop.
← ← member (X, [c]).
X/b

← ← member (X, []).


X/c

door(s,a).
Search i prolog door(a,b).
door(b,c).
Search, new door e-b
door(c,d).
door(d,e).
door(s,a). d e f door(e,b). %now loop can happen d e f
door(a,b). door(e,f).
door(b,c).
go(A,B):-door(A,B).
door(c,d). s go(A,C):-door(A,X), go(X,C).
s
door(d,e).
c b a c b a
door(e,f). ?- go(s,f).
Stack overflow

go(A,B):-door(A,B). % If there is a door between A and B then we succeed in go(A,B, _):-door(A,B).


reaching B go(A,B,V):-door(A,X), \+ member(X, V), go(X,B, [X|V]).
go(A,B):-door(A,X), go(X,B).
% There is a door between A and X and
?- go(s,f).
% one can go from X to B then succeed in reaching B Yes

?- go(s,f). go2(A,B,V,P):-door(A,B), V = P.
Yes go2(A,B,V,P):-door(A,X), \+ member (X, V), go2(X,B, [X|V], P).
?- go2(s,f, [], P).
P = [a,b,c,d,e,f]

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 9
2008-09-18

Meta-logic predicate
These are what are required to write a
Prolog contains a uppsättning predicate which is not
strict predicate logic. One can also write program which Prolog program.
change its own code (important property within AI).
?- write(”hello world ”), writeln(5).
hello world 5 The rests is hard work to train yourself
 var(X) – fails if X is instantialized. to jump out of imperative
Example:
?− X = Y, var(X).
programming. Think in a declarative
yes way in Prolog programming.
?- Z = hej, var(Z).
no
?− var(sun).
no Read some Prolog tutorials on web!


integer( X) - if X is bound to an integer.
atomic(X) - if X is bound to a constant End

Introduction to Artificial Intelligence, Prolog


(c) Peter Funk 10

Você também pode gostar