introduction to prolog programming in logicnxg01/aicourse/lecture 5.pdf2008-09-18 introduction to...
TRANSCRIPT
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 1
Crash Course in Prolog Artificial Intelligence ���
MHD
Introduction to PROLOG PROgramming in LOGic
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.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 2
Important to know about Prolog
n Basics in Prolog: facts, lists [], meta-logical predicates, accumulator, tail-recursion, (DCG), generate-and-test, search.
n Connection to other areas: Relational data-baser, Expert systems, Formal and automata-theory, (Natural language processing).
n To think declarative.
Traditional Programming
Imperative programming: § An abstraction of the Turing machine (a
program is instructions to a Turing machine).
§ Have an ”operational semantic” in terms of what the Turing machine has to perform.
§ Is context dependent (what operations have been made before).
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 3
Logic programs
n A description in a suitable logical notation describing a part of the real world or a fictive world.
n Description of al needed to solve a task:
->relations between objects in a world (people, numbers, lists, trees, …).
Logic and Programming
A logic has 4 parts · syntax (describing logical formulas) · semantic (exact meaning) · a number of axioms (e.g. Tautologies: [a] = [a|[]] } · inference rules (e.g. modus ponens, “if a so b”)
Logics: First order logic, predicate logic, typed
logic, temporal logic (events, intervals, …), modal logic (probability, maybe, true in all worlds,…)
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 4
Prolog & Logic today: n Prolog is used for prototypes n Some larger commercial systems (links to .exe and
users often not aware that system is in Prolog). n Compilation and Interpretation systems (Erlang used
at Ericsson is initially written in Prolog, used to program telephone exchanges).
n Graphic packets, fast execution, database acces, e.g mySQL, good interfaces to other programming languages (calls to/from e.g. C++/Java/PHP).
n Used in natural language processing, interpretation, translation etc.
n Good interfaces to web applications, web pages can use prolog (exv. LPA-Prolog – html – php - mySQL).
Status today for Logic and Logic programming:
n formal verification of safety critical systems (landnings wheels in air plains, train signals, medical hardware, etc).
n Hardware design (TTL-logic circuit, true=1=5 volt, false=0=0 volt), predicate logic, temporal logic, modal logic
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 5
Future for Prolog? n Knowledge representation (SDL, XML,
Relation databases -> Knowledge bases, natural language), temporal logic.
n Safety critical systems need proof of their correctness n Air plane, transportation, telecommunication,
medicine, etc (programs i C are very difficult to prove !).
n Prolog is developed: n Constraint Logic Programming (CLP): n parallel-execution n Agent programming n web programming
Declarative description ~ Imperative Example for declarative description
Find all grand children of a certain person X. Declarative description
A grand child of X is a child of one of X’s children Imperative description
In order to find on grand child of X, first find one child of X, and then find a child of this child.
Imperative description II To find a grand child of X, first find a parent of one child, then check if the parent is a child of X.
• Logic: ∀ X ∀ Y (∃ Z
(child(X, Z) and child(Z, Y)) → grandchild(X, Y)). Prolog: grandchild (X,Y) :- child(X,Z), child(Z,Y).
read(person); for i := 1 to max_child do if child[i,1] = person then for j := 1 to max_child do if child[j,1] = child[i,2] then writeln(child[j,2]); fi od fi od
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 6
Declarative and imperative languages
Imperative language
Declarative language
Philosophy Apply instructions of how to solve the problem
Apply descriptions of what the problem is
Program
A sequence of commands
A set of assertions
Example
Basic, C, C++, Ada, Java, Perl, php, Phyton, …
Prolog, ML, Scheme, Gödel, mercury, Oz, (SQL), …
Strength Fast and specialized program
General, readable and possibility of correct program
Different Language paradigms n imperative languages are concrete and
enforcing, i.e., a given execution order. ”high level instructions to a processor”.
declarative program: n Nothing about how it should be executed
(true in ”pure Prolog”). n Describe only the problem and the
information of the problem. n Origin in logic and how humans make
logical reasoning.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 7
Logic History 400 fK The first foundation was built by Aristoteles (axiom, premise,
conclusion “Alla valar är däggdjur" osv). 1930 Subject stabilized [Gödel, Church, Russel, etc.]. (Predicate logic
complete kartlagt Church-Turing-sentence => predicate logic == calculable funktions)
1960 Automatic Theorem Proving & AI. 1965 Resolution and unification [Robinson]. Resolution: an effective
conclusion drawing but rules must be written in a special form. 1972 The first Prolog-implementation [Colmerauer]. 1974 Logic programming (SLD-resolution) [Kowalski] (Algoritm = logic +
control, let computers decide how the problem should be solved, i.e., execution ord).
1977 Negation (SLDNF-resolution) [Clark]. (SLDNF completed negative assertion “A penguin can not fly").
1978 Edinburgh Prolog [Warren] (most common syntax today). 1981 Japanese announce its 5:e-generation project: robotic, AI, etc, with
logic programming (”main result”: increased use of computers in Japan with Kanji, romaji).
1995 – Constraint Logic Programming (CLP), Agent Programming (logic bubblor), …
Some Important Notes (Logic)
n Predicate name is a name standing for both property and relation. green(grass). child(kai,mia)
n Predicate name is followed by arguments. Arity gives the number of arguments of the
predicate. n Arity= 0: satslogik (no argument) n Arity= 1:property n Arity= 2: relation
n Arguments are called terms. A term can be constant, variable or a structure.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 8
Del 2: Test Prolog n Free Prolog for Education (Linux/Mac/
Windows): http://www.swi-prolog.org/ Small space ( 4 Meg). Many Prolog introductions on web, search with
www.google.com for Prolog tutorial introduction
Prolog is different
n Prolog has no global variables. n No variable assignment statements n No iterative constructions (e. g. loop) n No ”if … then” format n Recursion is central in Prolog
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 9
Concept in Prolog n True or false, a Prolog expression can only
accept two values, true or false n Two arguments can be equal or different.
Equality can be obtained by binding free variables. lecturer(peter) = lecturer(X).
n Search, Prolog is based on searching, Prolog tries to find a solution and test different ways.
n Backtracking, if search fails, Prolog goes back and tests alternative ways (depth first).
Property Written as man(adam). man(kalle). man(lasse). woman(lisa). woman(eva).
RELATIONs written as: parent(adam,peter). % adam is parent of peter parent(eva,kalle). parent(eva,lisa). parent(lisa,lasse). parent(kalle, knut). Rest text after % is
comment
% Complete always with a point.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 10
Definition of Rule
Every rule has a head – name which defines the relation.
Every rule has a body – self definition of the relation. Definitions of father and mother are as follows:
”If M is a woman and M is parent of C then M is mother of C”: mother(M,C):- woman(M), parent(M,C).
”If F is a man and F is parent of C then F is father of C”: father(F,C):- man(F), parent(F,C).
”,” means logic ”AND”, both man och parent must be true in order for father to be true.
”:-” means logic implikation, ← but this is not available on keyboard, so prolog has adopted :-
Prolog Interpretations n Facts and rules are written in file which have
ending .pl n Dropp the file on the prolog icon or load prolog file
(se manual). Ask Prolog I there are any women.
| ?- woman(X). X = lisa ? ; X = eva ? ; no | ?-
typing ”;” after a answer asks prolog for more alternative answers.
Prolog Prompt: Prolog always prompts ”?-”. After the prompt you can enter your question.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 11
If we only whish to know if ther is a women. | ?- woman(_). yes | ?- child(_). no
Prolog is based on ”negation as failure”, all prolog does not know is false (will talk more about this later).
The prolog history with it’s roots in Edinburgh and Scotland makes Whiskey (distillated beer put in an ok barrel 3 years or more) examples common.
Write this in a textfile with the ending “.pl” ;
whisky(bowmore). whisky(glenlivet). region(bowmore, islay). region(glenlivet, highland). age(bowmore, 12).
Is there a whisky from Islay and how old is the whisky? | ?- region(W, islay), age(W, A). A = 12, W = bowmore ? ; no | ?-
W is instantiates to (binds to) bowmore.
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 12
whisky(bowmore). region(bowmore, islay). age(bowmore, 12).
Is there a whisky older than 8 years? | ?- whisky(W), age(W, A), A>8. A = 12, W = bowmore ? ; no | ?-
Structure 3 different ways to write the same facts: taste(oban, 16, taste, peat, medium, smoky, medium, body,
medium). taste(oban, 12, [peat, medium], [smoky, medium], [body,
medium]). taste(oban, 12, [[peat, medium], [smoky, medium], [body,
medium] ]). taste(oban, 10, taste(peat(medium), smoky(medium), body
(medium))). Warning, it is easy to misunderstand structures in
Prolog, there are no functions in Prolog!
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 13
taste(oban, 10, taste(peat(me), smoky(me), body(me))).
| ?- taste(W, _, S). S = taste(peat(me), smoky(me), body(me)), W = oban ? ; no | ?-
taste(oban, 10, taste(peat(me), smoky(me), body(me))).
| ?- taste(W, _, taste(peat(T), _,_)). T = me, W = oban ? ; no | ?-
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 14
Mer REGLER whisky(bowmore). region(bowmore, islay). age(bowmore, 12). taste(bowmore,12, taste(peat(me), smoky(me),
body(me)).
man(peter). % All men M and whisky W is true that… % M likes W. likes(M, W) :- man(M), whisky(W).
What does Peter like? | ?- likes(peter, X). X = bowmore ? ; no | ?- \+ likes(peter,bowmore). no
whisky(bowmore). region(bowmore, islay). aalder(bowmore, 12). taste(bowmore,12, taste(peat(me), smoky(me), full(me)). man(peter). likes(M, W) :- man(M), whisky(W).
Negation, ”it is not true”, is written”\+”
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 15
Task
1) Add the fact that Kalle has a daughter Mia. 2) Write a clause that defines the relation cuisine,
e.g. answering who Mia is cuisine with. Extra: 3a) write a clause that defines grand mother. 3b)
Use this rule to show that Eva is Lasses grand mother. Preferable use a relation mother with two arguments (to show a predicate’s number of arguments the notation is “mother/2”).
man(adam). man(kalle). man(lasse). woman(lisa). woman(eva). woman(mia). parent(adam,lasse). % adam är förälder till lasse parent(eva,kalle). parent(eva,lisa). parent(lisa,lasse). parent
(kalle,knut). father(F,C):- man(F), parent(F,C). mother(M,C):- woman(M), parent(M,C).
Idea to answer (there are many different ways to solve it)
cousin(K1, K2):- parent(P1, K1), parent(P2, K2), sibling(P1,P2).
sibling(S1,S2):-
parent(X,S1), parent(X,S2), S1 \== S2. % S1 and S2 can not be the same person,
% you can not be a sibling with yourself J
Test i Prolog ?- kusin(X,Y). X = lasse Y = knut ; no
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 16
Lists n [ ] : an empty list n [1, 2, abba] : a lista with 3 elements n [[11, 12, 13], [21, 22, 23], [31, 32, 33]] :
a 3x3 matrix (a list with 3 rows where every row has 3 columns).
Lists Head of a list, tail of a list, analogy with
CAR and CDR in LISP These two lists are identical! ?- [a,b,c] = [a|[b,c]]. Yes ?- [a,b,c] = [Head|Tail]. Head=a Tail=[b,c] | ?-
Gives the head and the tail
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 17
Some basic clauses: member % Clause member % X is member in a list if it is the first element in
the list, e.g is a member of [a,b,c] member(X, [X|Tail]). member(a,[a|[b,c]]).
% If not, then X needs to be in the tail. member(X, [First|Tail]) :- member (X, Tail). ---- | ?- member(1, [abba, 1, 3]). yes
Tail recursion= if the last predicate is the predicate itself. As efficient as a loop in C if execution time is an issue.
member member(X,L) :- L = [X|Rest]. member(X,L) :- L = [F|Rest], member(X, Rest). | ?- member(X, [abba, 1, 3]). X = abba ? ; X = 1 ? ; X = 3 ? ; no | ?-
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 18
member | ?- member(1, [A, B]). A = 1 ? ; B = 1 ? ; no | ?-
Tricky, A and B are variables and may be anything, e.g. 1. So both the first elements may be ”1” and the second element in the list may be ”1”.
first, second, tail % First element in list. first(X, [X|_]). % Second element in list. second(X, [ _,X|_ ]). % Rest of list. tail(R, [ _|R]).
| ?- first(X, [kalle,lisa,mats]). X = kalle? ; no | ?- | ?- second(X, [kalle,lisa,mats]). X = lisa? ; no | ?- | ?- tail(X, [kalle,lisa,mats]). X = [lisa,mats]? ; no | ?-
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 19
Aritmetic an others n A condition is true or fals: <, >, >=, =<,
=:=, =\= (reduces left and right side ). n is (exempel ?- X is 4 + 3) n ==, \== (exact equal) n = (unification, Prolog tries to bind all
unbound variables as far as possible. If Prolog succeeds it is called a successful unification).
n +, -, *, /, sin, cos, tan
| ?- 2 =< 4. yes | ?- 2+2 =:= 4. yes | ?- 2+2 =:= 5. no | ?- 2+2 =\= sin(0), 0 + 0 =:= sin(0). yes
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 20
Trace | ? - trace, X is sin(4/5), X>2. 1 1 Call: _59 is sin(4/5) ? <ENTER> 1 1 Exit: 0.71735609 is sin(4/5) ?
<ENTER> 2 1 Call: 0.71735609 > 2 ? <ENTER> 2 1 Fail: 0.71735609 > 2 ? <ENTER> 1 1 Redo: 0.71735609 is sin(4/5) ?
<ENTER> 1 1 Fail: _59 is sin(4/5) ? <ENTER>
”Redo” meens that Prolog interprer backtracks (backs one or more steps to try to find an other solution).
A is B. B is calculated and unified with the variable och
constant A. | ? - Area is 3.14 * 5 * 5. Area = 78.5 ? <ENTER> yes | ? - 4 is 4. yes | ? – X is 2 + M. ERROR | ? – M = 2, X is 2 + M. X = 4
• To calculate the right side of ”is” no unbound variables are
alowed
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 21
Strictly equal ”==” | ?- V == Q. %variabel V is not strictly equal to Q % e.g. you may bind V with 1 and Q with 2 no | ?- V = 5, Q = 5, V == Q. %Now V and Q are strictly
equal yes | ?- 1+2 == 2+1. % structur 1+2 is not strictly 2 + 1 No | ?- 1+2 == 1+2. yes | ?- +(1,2) == 1+2. % structur 1+2 is strictly equal 2 +
1 yes
Unifying ’=’ Two predicats may be unified if and only if n They have the same name n They have the same amount of
arguments Arguments can be unified Two arguments may be unified if and only if n Both are the same constant n Both are structures...
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 22
Unification ”=”
Two structures may be unified if and only if
n They have the same constructor (namn, e.g. +, peat, ..)
n They have the same number of arity (same number of parameters)
n The parameters can be unified
Exampel on unifification -1 | ?- xx(left, 123, X) = xx(A,B,B). A = left, B = 123, X = 123 ? ; | ?- cbc = X. X = cbc ? | ?- +(5,5) = 5 + 5 yes Why does this example fail? | ?- X = 5 + 5, X = 10. no
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 23
Example on unification 2 | ?- E = 1+2. E = 1+2 ? <ENTER> Yes (E has beed bound to the structure
”1+2” which is equal to +(1,2) | ?- p(p(p(p(0)))) = p(p(X)). X = p(p(0)) ? ; no | ?-
Example on unification 3a
% predikatet lenght1 length1(0, [ ]). length1(N, [ F|R]) :- length1(N2, R), N = N2+1.
| ?- length1(X, [a,b,c]). X = 1+(1+(1+0)) ? ; no | ?-
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 24
Example on unification 3b
% predicat: lenght1 length1(0, [ ]). length1(N, [ F|R]) :- length1(N2, R), N is N2+1.
| ?- length1(X, [a,b,c]). X = 3; no | ?-
Syntax n Predicat: mamma, mMM, no_1_. n Variables: W, W12, _12 n Constanter: stefan, sTEFAN, ’Stefan’ n Structurer: node(node(X,10,nil),12,nil). n Lists: [], [1,2, [44, 55], 3], [a,n(1,2,3)] n Arithmetik : +, -, *, /, sin, cos, tan, <, >,
>=, =<, =:=, =\=, ==, =, is
n numbers: 0,…, 9, 123.31, 55.2e-3
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 25
Closed world assumption (CWA)
Exempel: SJ says that there is a train from Stockholm at 8:07. But it is not mentioned that there is NO train at 8:10 or 8:15.
Since nothing is mentioned about a train leaving at 8:15 then there is most likely no train.
CWA: Things not mentioned are noDet som inte kan visas är inte sant.
Negation as Failure: NF: Everything the program can nDet som
Prologprogrammet inte kan härleda i ändlig tid är falskt.
Negation i Prolog
”Negation by failure” is written i prolog as ”\+” Exemple: ?- X = z, \+ member(X,[a,b,c]). yes ?- X = c, \+ member(X,[a,b,c]). no
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 26
How does Prolog find all solutions n Depth-first with backtracking: n Once a leaf is reached the interpreter
backs up and takes the first found branch to the left.
n Problem: infinite sub trees ⇒ program execution never ends.
SLD-tree for ← member(X, [a, b, c])."
Program: member(X, [X|_]). member(X, [_|T]) :- member(X, T).
← member(X, [a, b, c]).
← ← member(X, [b, c]). X/a ← ← member(X, [c]). X/b ← ← member(X, []). X/c
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 27
Search in prolog
door(s,a). door(a,b). door(b,c). door(c,d). door(d,e). door(e,f). move(A,B):-door(A,B). % Is there a door between A and B then we can
reach B move(A,B):-door(A,X), move(X,B).
%is there a door between A and X % is it possible to get from X to B then we succeeded to go from A to B ?- move(s,f). Yes
a b c
d e f
s
Search, new door e-b door(s,a). door(a,b). door(b,c). door(c,d). door(d,e). door(e,b). %now risk for loop door(e,f).
move(A,B):-door(A,B). move(A,C):-door(A,X), move(X,C).
?- move(s,f). Stack overflow
a b c
d e f
s
move(A,B, _):-door(A,B). move(A,B,V):-door(A,X), \+ member(X, V), move(X,B, [X|V]). ?- move(s,f). Yes move2(A,B,V,P):-door(A,B), V = P. move2(A,B,V,P):-door(A,X), \+ member(X, V), move2(X,B, [X|V], P). ?- move2(s,f, [], P). P = [a,b,c,d,e,f]
2008-09-18
Introduction to Artificial Intelligence, Prolog (c) Peter Funk 28
Metalogic predicat " Prolog contains a number of predicate that are not strictly first
order logic. You may also write programs able to change their own code (an important feature for AI)."
"
?- write(”hello world ”), writeln(5). hello world 5 n var(X) – fails if X is bound to a constant.
Exempel:""
?- X = Y, var(X). yes"?- Z = hello, var(Z)."no"?- var(sol). no "• integer( X) - true ifX is bound to a number."• atomic(X) - true if X is bound to a constant.
This is all knowledge needed to write Prolog programs.
The rest is hard work, practice in
thinking descriptive and exercise your brain out of imperative programming
Read more Prolog tutorials on the
web!