Agile Software Development LabDr. Günter Kniesel, Daniel Speicher, Tobias Rho
Prolog - Part 2
Spring 2008
Patrick Rypalla
Alexis Raptarchis
Prolog: Language and essential logic programming techniques 2
Lists
� A list is a finite sequence of elements.
� Example of a list in Prolog:
[mia, vincent, jules, yolanda]
[]
Agile Software Development Lab , Spring 2008
[]
[[ ], dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]]
� List elements are enclosed in square brackets
� Elements are eparated by comas
� There is a special list: The empty list []
� All sorts of Prolog terms can be elements of a list
Prolog: Language and essential logic programming techniques 3
Lists: Head and Tail
� A non-empty list consists of two parts:
� The head:
� The head is the first element of the list.
� The tail:
� The tail is what remains once we have removed the head.
� The tail of a list is always a list.
Agile Software Development Lab , Spring 2008
� The tail of a list is always a list.
� What about the empty list?
� The empty list has neither a head nor a tail
� Plays an important role in recursive predicates for list processing.
Prolog: Language and essential logic programming techniques 4
Lists: Head and Tail
� Some examples:� [mia, vincent, jules, yolanda]
Head: mia
Tail: [vincent, jules , yolanda]
� [[ ], dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]]
Agile Software Development Lab , Spring 2008
Head: []
Tail: [dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]]
� [dead(x)]
Head: dead(x)
Tail: []
Prolog: Language and essential logic programming techniques 5
Lists: The Operator |
� The built-in Prolog operator | is used to decompose a list into its head and tail:
?- [X|Y] = [mia, vincent, jules, yolanda].
X = mia
Agile Software Development Lab , Spring 2008
X = miaY = [vincent,jules,yolanda]yes
?-
Prolog: Language and essential logic programming techniques 6
Lists: The Operator |
� The built-in Prolog operator | is used to decompose a list into its head and tail:
?- [X|Y] = [ ].
no
Agile Software Development Lab , Spring 2008
no
?-
Prolog: Language and essential logic programming techniques 7
Lists: The Operator |
� We can also use | to split a list at any point:
?- [X,Y|Tail] = [[ ], dead(z), [2, [b,c]], [], Z, [2, [b,c]]] .
X = [ ]Y = dead(z)
Agile Software Development Lab , Spring 2008
Y = dead(z)Z = _4543 Tail = [[2, [b,c]], [ ], Z, [2, [b,c]]] yes
?-
Prolog: Language and essential logic programming techniques 8
Lists: The Operator |
� Suppose we are interested in the second and fourth element of a list:
?- [X1,X2,X3,X4|Tail] = [mia, vincent, marsellus, jody, yolanda].X1 = miaX2 = vincentX3 = marsellus
Agile Software Development Lab , Spring 2008
� X1,X3 and Tail aren’t of any interest for us.
X3 = marsellusX4 = jodyTail = [yolanda]yes
?-
Prolog: Language and essential logic programming techniques 9
Lists: The Anonymous Variable _
� The anonymous variable is used when you need to use a variable, but you are not interested in what Prolog instantiates it to.
� Each occurrence of the anonymous variable is independent, i.e. can be bound to something different.
Agile Software Development Lab , Spring 2008
?- [ _,X2, _,X4|_ ] = [mia, vincent, marsellus, jody, yolanda].X2 = vincentX4 = jodyyes
?-
Prolog: Language and essential logic programming techniques 10
Lists: member/2
� One of the most basic things we would like to know is whether a term X is an element of list L.
� So we need a predicate that when given a term X and a list L, tells us whether or not X belongs to L:
member(X,[X|T]).
Agile Software Development Lab , Spring 2008
� This predicate recursively works its way down a list
� doing something to the head, and then
� recursively doing the same thing to the tail.
� Very important Prolog technique
member(X,[H|T]):- member(X,T).
Prolog: Language and essential logic programming techniques 11
Lists: member/2
� In order to force attention to what is essential we could replace the unnecessary variables with anonymous variables:
member(X,[X|T]).
member(X,[H|T]):- member(X,T).
Agile Software Development Lab , Spring 2008
member(X,[X|_]).
member(X,[_|T]):- member(X,T).
Prolog: Language and essential logic programming techniques 12
Lists: member/2
� A test run of member:
member(X,[X|_]).
member(X,[_|T]):- member(X,T).
?- member(vincent,[yolanda,trudy,vincent,jules]).yes
Agile Software Development Lab , Spring 2008
yes?- member(X,[yolanda,trudy,vincent,jules]).X = yolanda;X = trudy;X = vincent;X = jules;no?-
Prolog: Language and essential logic programming techniques 13
Lists: Excercise
� Write a predicate a2b/2 that takes two lists as arguments and succeeds
� if the first argument is a list of as and� the second argument is a list of bs and� the two lists are of equal length.
?- a2b([a,a,a,a],[b,b,b,b]).
Agile Software Development Lab , Spring 2008
� Hint: Ask yourself “Are two empty lists equal?”. This is the base case.
?- a2b([a,a,a,a],[b,b,b,b]). yes?- a2b([a,a,a,a],[b,b,b]). no?- a2b([a,c,a,a],[b,b,b,t]). no
Prolog: Language and essential logic programming techniques 14
Lists: Excercise
� Solution:
� Often a good strategy is to
a2b([],[]).
a2b([a|L1],[b|L2]):- a2b(L1,L2).
Agile Software Development Lab , Spring 2008
� think about the simplest possible case
� Now think recursively! When should a2b/2 decide that two non-empty lists are a list of as and a list of bs of exactly the same length?
Prolog: Language and essential logic programming techniques 15
Arithmetic in Prolog
� Prolog offers a number of basic arithmetic tools:
2 + 3 = 53 x 4 = 125 – 3 = 23 – 5 = -2
?- 5 is 2+3.?- 12 is 3∗4.?- 2 is 5-3.?- -2 is 3-5.
Arithmetic Prolog
Agile Software Development Lab , Spring 2008
3 – 5 = -24 : 2 = 21 is the remainder when 7 is
divided by 2
?- -2 is 3-5.?- 2 is 4/2.?- 1 is mod(7,2).
?- 10 is 5+5.yes?- 4 is 2+3.no
Prolog: Language and essential logic programming techniques 16
Arithmetic in Prolog
� It is important to know that +, -, / and ∗ do not , on their own, carry out any arithmetic.
� Expressions such as 3+2, 4-7, 5/5 are ordinary Prolog terms just used in user friendly notation.� Functor: +, -, /, ∗� Arity: 2
Agile Software Development Lab , Spring 2008
� Arity: 2
� Arguments: integers
� This leads to:?- X = 3 + 2.X = 3+2yes?- 3 + 2 = X.X = 3+2yes
Prolog: Language and essential logic programming techniques 17
Arithmetic in Prolog: The is/2 predicate
� To force Prolog to actually evaluate arithmetic expressions, we have to use the is predicate.
� This is not an ordinary predicate there are some restrictions:
Agile Software Development Lab , Spring 2008
?- X is 3 + 2.X = 5yes
?- 3 + 2 is X.ERROR: is/2: Arguments are not sufficiently instantiated
Prolog: Language and essential logic programming techniques 18
Arithmetic in Prolog: Restrictions of the is/2 pred icate
1. We are free to use variables on the right hand side of the is predicate.
2. But when Prolog actually carries out the evaluation, the variables must be instantiated with a variable-free Prolog
Agile Software Development Lab , Spring 2008
variables must be instantiated with a variable-free Prolog term.
3. This Prolog term must be an arithmetic expression.
Prolog: Language and essential logic programming techniques 19
Arithmetic in Prolog: Arithmetic and Lists
� How long is a list?
� The empty list has a length of zero.
� A non-empty list has a length of one plus the length of it’s tail.
len([],0).
len([_|L],N):- len(L,X), N is X + 1.
Agile Software Development Lab , Spring 2008
len([_|L],N):- len(L,X), N is X + 1.
?- len([a,b,c,d,e,[a,x],t],X).X=7yes
Prolog: Language and essential logic programming techniques 20
Accumulator
� There is another way of finding out the length of a list using an accumulator:
� Accumulators are variables that hold intermediate results.
� The predicate acclen/3 has three arguments
Agile Software Development Lab , Spring 2008
� The predicate acclen/3 has three arguments
1. The list whose length we want to find
2. The length of the list, an integer
3. An accumulator, keeping track of the intermediate values for the length
Prolog: Language and essential logic programming techniques 21
Accumulator
� The accumulator of acclen/3:� Initial value of the accumulator is 0
� Add 1 to accumulator each time we can recursively take the head of a list
� When we reach the empty list, the accumulator contains the length of the list
Agile Software Development Lab , Spring 2008
acclen([],Acc,Acc).
acclen([_|L],OldAcc,Length):-
NewAcc is OldAcc + 1,
acclen(L,NewAcc,Length).
?-acclen([a,b,c],0,Len).Len=3yes
Prolog: Language and essential logic programming techniques 22
Tail-Recursive
� Which predicate is better?
� acclen/3 because it is tail-recursive.
� Difference between tail recursive and recursive:
Agile Software Development Lab , Spring 2008
� In tail recursive predicates the results is fully calculated once we reach the base clause.
� In recursive predicates that are not tail recursive, there are still goals on the stack when we reach the base clause.
Prolog: Language and essential logic programming techniques 23
Non Tail-Recursive len/2
� Search tree for len/2 :?- len([a,b,c], Len).
/ \
no ?- len([b,c],Len1), Len is Len1 + 1.
/ \
no ?- len([c], Len2),
len([],0).
len([_|L],NewLength):-
len(L,Length),
NewLength is Length + 1.
Agile Software Development Lab , Spring 2008
no ?- len([c], Len2), Len1 is Len2+1, Len is Len1+1.
/ \
no ?- len([], Len3), Len2 is Len3+1, Len1 is Len2+1,
Len is Len1 + 1./ \
Len3=0, Len2=1, no
Len1=2, Len=3
Prolog: Language and essential logic programming techniques 24
Tail-Recursive acclen/3
� Search tree for acclen/2 :
?- acclen([a,b,c],0,Len).
/ \
no ?- acclen([b,c],1,Len).
/ \
acclen([ ],Acc,Acc).
acclen([_|L],OldAcc,Length):-
NewAcc is OldAcc + 1,
acclen(L,NewAcc,Length).
Agile Software Development Lab , Spring 2008
/ \
no ?- acclen([c],2,Len).
/ \
no ?- acclen([],3,Len).
/ \
Len=3 no
Prolog: Language and essential logic programming techniques 25
Arithmetic in Prolog: Comparing Integers
� Operators that compare integers actually do carry out arithmetic by themselves:
x < yx ≤ yx = y
X < YX =< YX =:= Y
Arithmetic Prolog
Agile Software Development Lab , Spring 2008
� These have the obvious meaning.
� Force both left and right hand argument to be evaluated.
x = yx ≠ yx ≥ yx > y
X =:= YX =\= YX >= YX > Y
Prolog: Language and essential logic programming techniques 26
Arithmetic in Prolog: Comparing Integers
� Some examples:
?- 2 < 4+1. yes
?- 4+3 > 5+5.no
Agile Software Development Lab , Spring 2008
?- 4 = 4. yes
?- 2+2 = 4. no
?- 2+2 =:= 4.yes
Prolog: Language and essential logic programming techniques 27
Arithmetic in Prolog: Exercise
� Define a predicate accMax/3 that takes three arguments, and is true when:� The first argument is a list of positive integers and
� The third argument is the highest integer in the list.
� The second argument is the initialization of the accumulator
?- accMax([1,0,5,4],0,Max).
Agile Software Development Lab , Spring 2008
� Hint: Use the accumulator to keep track of the highest value encountered so far.
?- accMax([1,0,5,4],0,Max).Max=5yes
Prolog: Language and essential logic programming techniques 28
Arithmetic In Prolog: Excercise
� Solution:
accMax([H|T],A,Max):-
H > A,
accMax(T,H,Max).
accMax([H|T],A,Max):-
Agile Software Development Lab , Spring 2008
accMax([H|T],A,Max):-
H =< A,
accMax(T,A,Max).
accMax([],A,A).
Prolog: Language and essential logic programming techniques 29
Other useful predicates for lists: append/3
� append(L1,L2,L3)
append([], L, L).
append([H|L1], L2, [H|L3]):-
append(L1, L2, L3).
Agile Software Development Lab , Spring 2008
� Base clause: appending the empty list to any list produces that same list
� The recursive step says that when concatenating a non-empty list [H|T] with a list L, the result is a list with head H and the result of concatenating T and L
Prolog: Language and essential logic programming techniques 30
Other useful predicates for lists: append/3
� We can also use append/3 to define other useful predicates like prefix/2:
� A list P is a prefix of some list L when there is some list such
prefix(P,L):-
append(P,_,L).
Agile Software Development Lab , Spring 2008
� A list P is a prefix of some list L when there is some list such that L is the result of concatenating P with that list.
� How about suffix/2 ?
suffix(S,L):-
append(_,S,L).
Prolog: Language and essential logic programming techniques 31
Other useful predicates for lists: Naïve reverse
� naiveReverse/2
naiveReverse([],[]). naiveReverse([H|T],R):-
naiveReverse(T,RT),append(RT,[H],R).
Agile Software Development Lab , Spring 2008
� If we reverse the empty list we get the empty list.
� If we reverse the list [H|T], we end up with the list obtained by reversing T and concatenating with [H].
� naiveReverse/2 does an awful lot of work. Isn’t there a better way?
append(RT,[H],R).
Prolog: Language and essential logic programming techniques 32
Other useful predicates for lists: reverse
� reverse/2:� Use a list as an accumulator.
� Take the head of the list that we want to reverse and add it to the head of the accumulator list.
� When we hit the empty list , the accumulator will contain the reversed list!
Agile Software Development Lab , Spring 2008
accReverse([ ],L,L).
accReverse([H|T],Acc,Rev):-
accReverse(T,[H|Acc],Rev).
reverse(L1,L2):-
accReverse(L1,[ ],L2).
Prolog: Language and essential logic programming techniques 33
Other useful predicates for lists: Exercise
� Define a predicate sublist/2 that finds sub-lists of lists.� Hint: Use already known predicates.
� Solution:� The sub-lists of a list L are simply the prefixes of suffixes of L
Agile Software Development Lab , Spring 2008
sublist(Sub,List):-
suffix(Suffix,List),
prefix(Sub,Suffix).
Prolog: Language and essential logic programming techniques 34
The Cut
� Backtracking is a characteristic feature of Prolog but can often lead to inefficiency
� Prolog can waste time exploring possibilities that go nowhere.
� The cut predicate !/0 offers a way to control backtracking.
Agile Software Development Lab , Spring 2008
� Example:
� Cut always succeeds.
� Cut commits Prolog to the choices that were made since the parent goal was called.
p(X):- b(X), c(X), !, d(X), e(X).
Prolog: Language and essential logic programming techniques 35
The Cut
� In order to better explain the cut, we will
� Look at a piece of cut-free Prolog code and see what it does in terms of backtracking
� Add cuts to this Prolog code
Agile Software Development Lab , Spring 2008
� Examine the same piece of code with added cuts and look how the cuts affect backtracking
Prolog: Language and essential logic programming techniques 36
The Cut: cut-free code
p(X):- a(X).
p(X):- b(X), c(X), d(X), e(X).
p(X):- f(X).
a(1).
b(1). b(2).
c(1). c(2).
d(2).
e(2).
?- p(X).
?- a(X). ?- f(X).
?- c(1),d(1),e(1). ?- c(2),d(2),e(2).
?- b(X),c(X),d(X),e(X).
X=1X=1X=1X=1 X=1X=1X=1X=1
X=2X=2X=2X=2
X=3X=3X=3X=3
Agile Software Development Lab , Spring 2008
e(2).
f(3).
?- p(X).X=1;X=2;X=3;no
?- d(2), e(2).
?- e(2).
?- d(1), e(1).
?- c(1),d(1),e(1). ?- c(2),d(2),e(2).
††††
Prolog: Language and essential logic programming techniques 37
The Cut: cut
?- p(X).
?- a(X). ?- b(X),c(X),!,d(X),e(X).
X=1X=1X=1X=1
p(X):- a(X).
p(X):-b(X),c(X),!,d(X),e(X).
p(X):- f(X).
a(1).
b(1). b(2).
c(1). c(2).
d(2).
e(2).
X=1X=1X=1X=1 XXXX
XXXX
Agile Software Development Lab , Spring 2008
?- p(X).X=1;
e(2).
f(3). ?- c(1), !, d(1), e(1).
?- !, d(1), e(1).
?- d(1), e(1).
Prolog: Language and essential logic programming techniques 38
The Cut
� Consider the predicate max/3 which succeeds if the third argument is the maximum of the first two.
� Suppose it is called with ?- max(3,4,Y).
max(X,Y,Y):- X =< Y.
max(X,Y,X):- X>Y.
Agile Software Development Lab , Spring 2008
� Suppose it is called with ?- max(3,4,Y).
� It will correctly unify Y with 4
� But when asked for more solutions, it will try to satisfy the second clause. This is pointless!
� Better:max(X,Y,Y):- X =< Y, !.
max(X,Y,X):- X>Y.
Prolog: Language and essential logic programming techniques 39
Green Cuts , Red Cuts
� Cuts that do not change the meaning of a predicate are called green cuts.
� The cut in max/3 is an example of a green cut:
max(X,Y,Y):- X =< Y, !.
Agile Software Development Lab , Spring 2008
� the new code gives exactly the same answers as the old version,
� but it is more efficient
� Cuts that do change the meaning of a predicate are called red cuts.
max(X,Y,X):- X>Y.
Prolog: Language and essential logic programming techniques 40
The fail/0 predicate
� fail/0 is a special predicate that will immediately fail when Prolog encounters it as a goal.
� May not sound too useful but: When Prolog fails, it tries to backtrack!
Agile Software Development Lab , Spring 2008
backtrack!
� The combination of cut and fail allows us to code exceptions for our rules.
Prolog: Language and essential logic programming techniques 41
Exceptions
� An example:enjoys(vincent,X):-
bigKahunaBurger(X), !, fail.
enjoys(vincent,X):- burger(X).
burger(X):- bigMac(X).
burger(X):- bigKahunaBurger(X).
Agile Software Development Lab , Spring 2008
burger(X):- bigKahunaBurger(X).
burger(X):- whopper(X).
bigMac(a).
bigKahunaBurger(b).
bigMac(c).
whopper(d).
?- enjoys(vincent,b).no
Prolog: Language and essential logic programming techniques 42
Negation as failure
� The cut-fail combination lets us define a form of negation called negation as failure.
� For any Prolog goal, neg(Goal) will succeed precisely if Goal
neg(Goal):- Goal, !, fail.
neg(Goal).
Agile Software Development Lab , Spring 2008
� For any Prolog goal, neg(Goal) will succeed precisely if Goal does not succeed.
� cut blocks backtracking and then fail tries to force it.
� In standard Prolog the prefix operator \+ means negation as failure
enjoys(vincent,X):- burger(X),
\+ bigKahunaBurger(X).
Prolog: Language and essential logic programming techniques 43
Negation As Failure: Excercise
� What would happen if we changed the order of the goals in the burger example? That is if we had:
� Solution:
enjoys(vincent,X):- \+ bigKahunaBurger(X),
burger(X).
Agile Software Development Lab , Spring 2008
� Negation as failure is not logical negation!
?- enjoys(vincent,X).no
Prolog: Language and essential logic programming techniques 44
Meta-Predicates
� Meta-predicates are used to match, query, and manipulate other predicates in the problem domain.
� Examples of meta-predicates:� assert(Term) : adds Term to the current set of clauses.� retract(Term) : removes Term from the current set of clauses. � call(Clause) : succeeds with the execution of Clause
Agile Software Development Lab , Spring 2008
� call(Clause) : succeeds with the execution of Clause� clause(Head,Body) : unifies Body with the body of a clause
whose head unifies with Head
� Through meta-predicates Prolog can analyze, transform, and simulate other programs.
� It can even learn not only new data knowledge, but new procedural knowledge.
Prolog: Language and essential logic programming techniques 45
Summary
� We introduced lists and some recursive predicates that work on lists.
� The kind of programming that these predicates illustrated are fundamental to Prolog.
� We introduced the programming technique of using accumulators, which often offer an efficient solution.
Agile Software Development Lab , Spring 2008
accumulators, which often offer an efficient solution.
� Showed how exception are realized in Prolog and why they shouldn’t be thought of as a logical negation.
� Questions?