Computer Engineering Lab II

advertisement
CoE Software Lab II (2SBo6)
242-203, Semester 2, 2014-2015
Introduction to Prolog
Please ask
questions
Who I am:
Andrew Davison
WiG Lab Office
ad@fivedots.coe.psu.ac.th
242-203 Comp. Eng. II: Intro. to Prolog
1
1. Why Learn Prolog?
• Very popular in Artificial Intelligence (AI)
• Unique features include:
−unification (more powerful assignment)
−backtracking
−close links to predicate logic
• Very different from C, Java
−an engineer must know more than 1 tool
− Prolog is a logic programming language
241-203 Comp Eng Lab II: Intro. to Prolog
2
C Program Compared to Prolog
 void foo(...)
{ ... }
 Prolog predicate
-- made up of facts and rules
int bar(...)
{ ... }
Prolog predicate
void main()
{ ... }
?- Prolog query.
Lots of data types: int,
char, struct, pointer, ...
241-203 Comp Eng Lab II: Intro. to Prolog
-- more facts and rules
Data types: term, list
3
A Database Compared to Prolog
Staff Table
Database 
Prolog program
(many
predicates)
241-203 Comp Eng Lab II: Intro. to Prolog
1 Table  1 Predicate
Records  Facts
Record Data  Terms
4
2. Language Elements
• Terms
• Facts and Rules
• Predicates
241-203 Software Lab II: Intro. to Prolog
5
Terms are data
• Constants
adam paris 5 3.14 [] ´Adam’ ...
• Variables
X Y List _12 _ ...
• Compound terms (something like structs)
plus(2,3) foo(2,bar(a,'Jim')) ...
2+3
// infix notation
241-203 Software Lab II: Intro. to Prolog
6
Facts
(a bit like database records)
• A fact has the form p(t1,...,tn).
−p is the name of the fact
−t1, …, tn are term arguments of the fact
• Examples:
edge(a, b, 23).
note the '.'s
parent(andrew, john).
241-203 Software Lab II: Intro. to Prolog
7
Six Facts
parent(kim,holly).
parent(margaret,kim).
parent(margaret,kent).
parent(esther,margaret).
parent(herbert,margaret).
parent(herbert,jean).
note the '.'s
• Six facts about families:
− kim is the parent of holly
• Defines a predicate parent of arity 2
− called parent/2 for short
241-203 Software Lab II: Intro. to Prolog
8
• A predicate is a bit like a database table.
−6 facts in a family/2 predicate
similar to
−6 records in a family database table
• A logic program is a collection of predicates
−just like a database is a collection of tables
−the program on the previous slide only has 1
predicate (at the moment)
241-203 Comp Eng Lab II: Intro. to Prolog
9
parent/2 as a Graph
herbert
esther
parent
margaret
kim
jean
kent
holly
241-203 Software Lab II: Intro. to Prolog
10
Facts using more complex data
• A staff/3 predicate:
staff( name(mickey, mouse),
address(123, "Fantasy Way"), 73).
staff( name(bat, man),
address(321, "Cavern Ave"), 54).
staff( name(wonder, woman),
address(987, "Truth Way"), 39).
Based on the
db table example.
241-203 Software Lab II: Intro. to Prolog
11
more details in section 11
3. Executing Prolog
12
• Use a query to execute Prolog code.
−a query starts with "?-"
• In SB Prolog:
−use F5 (or Run|Run) to execute the query
−the output appears in the Output window
241-203 Software Lab II: Intro. to Prolog
13
3.1. Simple Queries
?- parent(margaret, kent).
Yes // printed in the Output window
?- parent(fred, pebbles).
No
241-203 Software Lab II: Intro. to Prolog
14
Executing a Query
• Match the query against a fact.
• Prolog tries each fact in top-down order,
until one matches, or it runs out of facts.
241-203 Comp Eng Lab II: Intro. to Prolog
15
3.2. Queries With Variables
?- parent(P, jean), write(P), write("\n")
herbert
the ',' means "and"
Yes
?- parent(P, esther), write(P), write("\n")
No
• Variable values are printed using write()
241-203 Software Lab II: Intro. to Prolog
16
Executing a Query
• Match the query
(e.g. ?- parent(P, jean))
against a fact
−also match (unify, bind) the variables
241-203 Comp Eng Lab II: Intro. to Prolog
17
3.3. Conjunctions
the ',' means "and"
?- parent(margaret,X), parent(X,holly),
write(X), write("\n").
kim
Yes
• A conjunction is a series of queries.
• Prolog works left to right, trying to match
each query.
241-203 Software Lab II: Intro. to Prolog
18
• As Prolog executes the queries in a
conjunction, it remembers variable
matches (bindings).
−e.g. the first query sets X = kim
−this value for X is passed to the second query
in the conjunction
241-203 Comp Eng Lab II: Intro. to Prolog
19
3.4. Multiple Solutions
the user types
'F8' to make
SB Prolog look
for another
answer
20
How Multiple Solns Work?
• When a query matches a fact, Prolog
remembers which fact was chosen
−called a choice point
• If the user types 'F8', Prolog goes back to
the choice point (backtracks) and tries
to find a different match.
241-203 Comp Eng Lab II: Intro. to Prolog
21
4. Rules
head
greatgrandparent(GGP,GGC) :parent(GGP,GP),
parent(GP,P),
parent(P,GGC).
body goals
• 1. Match query
(e.g. ?- greatgrandparent(margaret,holly)
against the head of a rule.
)
−match (unify) the variables
• 2. Create new query conjunction from the
body
goals.
241-203 Software Lab II: Intro. to Prolog
22
A Program With Two Predicates
parent(kim,holly).
parent(margaret,kim).
parent(margaret,kent).
parent(esther,margaret).
parent(herbert,margaret).
parent(herbert,jean).
greatgrandparent(GGP,GGC) :parent(GGP,GP), parent(GP,P), parent(P,GGC).
• parent/2 and greatgrandparent/2
predicates.
241-203 Software Lab II: Intro. to Prolog
23
Example
?- greatgrandparent(esther,GreatGrandchild),
write(GreatGrandchild), write("\n").
holly
Yes
241-203 Software Lab II: Intro. to Prolog
24
5. Recursive Rules
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :parent(Z,Y),
ancestor(X,Z).
base case
recursive case
• x is an ancester of y if
−x is the parent of y, or
−x is an ancester of z and
z is the parent of y
241-203 Software Lab II: Intro. to Prolog
the code
switches these
two body goals
around to speed up
execution
25
parent/2 again
herbert
esther
parent(kim,holly).
parent(margaret,kim).
parent(margaret,kent).
parent(esther,margaret).
parent(herbert,margaret).
parent(herbert,jean).
margaret
kim
jean
kent
holly
241-203 Software Lab II: Intro. to Prolog
26
ancestor/2 Queries
?- ancestor(kim,holly).
Yes
?- ancestor(A,holly),
write(A), write("\n").
kim
margaret // I typed F8
esther
// typed F8
herbert
// typed F8
No
// typed F8
241-203 Software Lab II: Intro. to Prolog
27
6. Operators
• Prolog systems have many built-in
operators. e.g.
=/2
is/2 and arithmetic
241-203 Software Lab II: Intro. to Prolog
28
The =/2 Predicate
• The goal =(X,Y) succeeds if X and Y
can be unified (matched)
• Usually written as X = Y
?- name(adam,seth) = name(adam,X),
write(X), write("\n").
seth
Yes
241-203 Software Lab II: Intro. to Prolog
29
Arithmetic Operators
• Terms +, -, * and / are operators, with
the usual precedence and associativity
?- X = +(1,*(2,3)), write(X).
1+2*3
?- X = 1+2*3, write(X).
1+2*3
241-203 Software Lab II: Intro. to Prolog
No evaluation of X.
30
Evaluating Arithmetic
?- X is 1+2*3, write(X).
7
yes
• The general format is:
Variable is expression
241-203 Software Lab II: Intro. to Prolog
31
7. Lists
List notation
[]
[andrew]
[1,2,"hello"]
[1,name(X,Y)]
241-203 Software Lab II: Intro. to Prolog
Meaning
an empty list
list with one element
3-element list
2-element list
32
Examples
?- X = [1, 2, 3].
X = [1, 2, 3]
?- [X, Y, Z] = [1, 2, 3].
From now on,
I'm going to
leave out
calls to write().
X = 1
Y = 2
Z = 3
241-203 Software Lab II: Intro. to Prolog
33
List Notation With Tail
?- [1,2|X] = [1,2,3,4,5].
X = [3, 4, 5]
• [1,2|X] matches with a list that starts
with 1,2 and binds X to the rest (tail) of
the list.
241-203 Software Lab II: Intro. to Prolog
34
?- [X|Y] = [a, b, dc, st, fg].
X = a
Y = [b, dc, st, fg]
241-203 Comp Eng Lab II: Intro. to Prolog
35
8. The append/3 Predicate
append([], B, B).
append([Head|TailA], B, [Head|TailC]) :append(TailA, B, TailC).
?- append([1,2],[3,4],Z), write(Z).
[1, 2, 3, 4]
Yes
• append(X,Y,Z) means that
the X list 'stuck onto' the Y list == the Z list
241-203 Software Lab II: Intro. to Prolog
36
Other Uses of append/3
?- append(X,[3,4],[1,2,3,4]), write(X).
[1, 2]
Yes
• append/3 can be called with variables in
any of its argument positions.
241-203 Software Lab II: Intro. to Prolog
37
Multiple Answers
?- append(X,Y,[1,2,3]).
X = []
Y = [1, 2, 3]
X = [1]
Y = [2, 3]
X = [1, 2]
Y = [3]
By using F8
X = [1, 2, 3]
Y = []
No
241-203 Software Lab II: Intro. to Prolog
38
9. Other List Predicates
Predicate
Description
member(X,Y)
Is X an element in the list Y?
length(X,Y)
Is the length of the list X equal to the Y value?
241-203 Software Lab II: Intro. to Prolog
39
member/2
member(X, [X|_]).
member(X, [Y|Rest]) :member(X, Rest).
?- member(1, [2, 1,3]).
yes
• member(X,L) succeeds
?- member(j, [a,n,d,y]).
no
if X is an element in
the list L
?- member(X,[j,i,m]),
write(X), write("\n").
j
i
// F8
m
// F8
no // F8
241-203 Software Lab II: Intro. to Prolog
40
length/2
length([], 0).
length([X|Rest], Len) :length(Rest, LenRest),
Len is LenRest + 1.
?- length([a,b,c,d], L), write(L).
4
?- length([1,2,3], 4).
no
• length(X,Y) succeeds if Y is the length
of the list X.
241-203 Software Lab II: Intro. to Prolog
41
10. The not/1 Predicate
?- not( member(4,[1,2,3]) ).
Yes
?- not( member(1,[2,1,3]) ).
No
• not(X) succeeds when the X goal fails.
• Only use not/1 when its goal contains no
variables.
−use not/1 as a yes/no test
241-203 Software Lab II: Intro. to Prolog
42
11. Using Strawberry Prolog
• Download SB Prolog system from:
http://fivedots.coe.psu.ac.th/
Software.coe/LAB/Prolog/
• The filename:
StrawberryProlog_3_0_Beta4.exe
• Read the readme.txt file
241-203 Software Lab II: Intro. to Prolog
43
Create a Prolog Program
using any text editor
saved in c:/windows/desktop/parents.pro
241-203 Software Lab II: Intro. to Prolog
44
• Or you can type into an SB Prolog
window, and save at the end.
−select File|New, and choose "Prolog File"
−at the end, select File|Save
241-203 Software Lab II: Intro. to Prolog
45
Running parents.pro
• Load the file using File|Open.
• Type in a query into the parents.pro
window:
− ?- parent(X, Y), write(X), write(" and "), write(Y).
• Select Run|Run from the menu
• Check the Output window
241-203 Software Lab II: Intro. to Prolog
46
12. More Information
• The Help menu in SB Prolog leads to:
−a tutorial
−a Prolog language guide
−examples
241-203 Software Lab II: Intro. to Prolog
continued
47
• SB Prolog’s Web Site:
− http://www.dobrev.com/light.html
−v.3.0 beta 4, and other versions
• A complete Prolog book (in PDF format):
− http://www.ida.liu.se/~ulfni/lpp/
• Online Prolog tutorials list at
− http://www.thefreecountry.com/documentation/
onlineprolog.shtml
241-203 Software Lab II: Intro. to Prolog
48
Download