1 / 45

Prolog - Part 2

Prolog - Part 2. Patrick Rypalla Alexis Raptarchis rypalla@cs.uni-bonn.de raptarch@cs.uni-bonn.de. Lists. A list is a finite sequence of elements. Example of a list in Prolog: [mia, vincent, jules, yolanda] [] [[ ], dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]]

carys
Download Presentation

Prolog - Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Prolog - Part 2 Patrick Rypalla Alexis Raptarchis rypalla@cs.uni-bonn.de raptarch@cs.uni-bonn.de

  2. Lists • A list is a finite sequence of elements. • Example of a list in Prolog: [mia, vincent, jules, yolanda] [] [[ ], 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

  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. 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.

  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]]] Head: [] Tail: [dead(z), [2, [b,c]], [ ], Z, [2, [b,c]]] [dead(x)] Head: dead(x) Tail: []

  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 Y = [vincent,jules,yolanda] yes ?-

  6. Lists: The Operator | The built-in Prolog operator | is used to decompose a list into its head and tail: ?- [X|Y] = [ ]. no ?-

  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) Z = _4543 Tail = [[2, [b,c]], [ ], Z, [2, [b,c]]] yes ?-

  8. Lists: The Operator | Suppose we are interested in the second and fourth element of a list: X1,X3 and Tail aren’t of any interest for us. ?- [X1,X2,X3,X4|Tail] = [mia, vincent, marsellus, jody, yolanda]. X1 = mia X2 = vincent X3 = marsellus X4 = jody Tail = [yolanda] yes ?-

  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. ?- [ _,X2, _,X4|_ ] = [mia, vincent, marsellus, jody, yolanda]. X2 = vincent X4 = jody yes ?-

  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: 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,[X|T]). member(X,[H|T]):- member(X,T).

  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). member(X,[X|_]). member(X,[_|T]):- member(X,T).

  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 ?- member(X,[yolanda,trudy,vincent,jules]). X = yolanda; X = trudy; X = vincent; X = jules; no ?-

  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. 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

  14. Lists: Excercise Solution: Often a good strategy is to 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? a2b([],[]). a2b([a|L1],[b|L2]):- a2b(L1,L2).

  15. Arithmetic in Prolog Prolog offers a number of basic arithmetic tools: Arithmetic Prolog 2 + 3 = 5 3 x 4 = 12 5 – 3 = 2 3 – 5 = -2 4  2 = 2 1 is the remainder when 7 is divided by 2 ?- 5 is 2+3. ?- 12 is 34. ?- 2 is 5-3. ?- -2 is 3-5. ?- 2 is 4/2. ?- 1 is mod(7,2). ?- 10 is 5+5. yes ?- 4 is 2+3. no

  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 Arguments: integers This leads to: ?- X = 3 + 2. X = 3+2 yes ?- 3 + 2 = X. X = 3+2 yes

  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: ?- X is 3 + 2. X = 5 yes ?- 3 + 2 is X. ERROR: is/2: Arguments are not sufficiently instantiated

  18. Arithmetic in Prolog: Restrictions of the is/2 predicate We are free to use variables on the right hand side of the is predicate. But when Prolog actually carries out the evaluation, the variables must be instantiated with a variable-free Prolog term. This Prolog term must be an arithmetic expression.

  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. ?- len([a,b,c,d,e,[a,x],t],X). X=7 yes

  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 The list whose length we want to find The length of the list, an integer An accumulator, keeping track of the intermediate values for the length

  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 acclen([],Acc,Acc). acclen([_|L],OldAcc,Length):- NewAcc is OldAcc + 1, acclen(L,NewAcc,Length). ?-acclen([a,b,c],0,Len). Len=3 yes

  22. Tail-Recursive Which predicate is better? acclen/3 because it is tail-recursive. Difference between tail recursive and recursive: 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.

  23. Non Tail-Recursive len/2 Search tree for len/2: len([],0). len([_|L],NewLength):- len(L,Length), NewLength is Length + 1. ?- len([a,b,c], Len). / \ no ?- len([b,c],Len1), Len is Len1 + 1. / \ 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

  24. Tail-Recursive acclen/3 Search tree for acclen/2: acclen([ ],Acc,Acc). acclen([_|L],OldAcc,Length):- NewAcc is OldAcc + 1, acclen(L,NewAcc,Length). ?- acclen([a,b,c],0,Len). / \ no ?- acclen([b,c],1,Len). / \ no ?- acclen([c],2,Len). / \ no ?- acclen([],3,Len). / \ Len=3 no

  25. Arithmetic in Prolog: Comparing Integers Operators that compare integers actually do carry out arithmetic by themselves: These have the obvious meaning. Force both left and right hand argument to be evaluated. Arithmetic Prolog x < y x  y x = y x  y x  y x > y X < Y X =< Y X =:= Y X =\= Y X >= Y X > Y

  26. Arithmetic in Prolog: Comparing Integers Some examples: ?- 2 < 4+1. yes ?- 4+3 > 5+5. no ?- 4 = 4. yes ?- 2+2 = 4. no ?- 2+2 =:= 4. yes

  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 Hint: Use the accumulator to keep track of the highest value encountered so far. ?- accMax([1,0,5,4],0,Max). Max=5 yes

  28. Arithmetic In Prolog: Excercise Solution: accMax([H|T],A,Max):- H > A, accMax(T,H,Max). accMax([H|T],A,Max):- H =< A, accMax(T,A,Max). accMax([],A,A).

  29. Other useful predicates for lists: append/3 append(L1,L2,L3) 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 append([], L, L). append([H|L1], L2, [H|L3]):- append(L1, L2, L3).

  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 that L is the result of concatenating P with that list. How about suffix/2? prefix(P,L):- append(P,_,L). suffix(S,L):- append(_,S,L).

  31. Other useful predicates for lists: Naïve reverse naiveReverse/2 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? naiveReverse([],[]). naiveReverse([H|T],R):- naiveReverse(T,RT), append(RT,[H],R).

  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! accReverse([ ],L,L). accReverse([H|T],Acc,Rev):- accReverse(T,[H|Acc],Rev). reverse(L1,L2):- accReverse(L1,[ ],L2).

  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 sublist(Sub,List):- suffix(Suffix,List), prefix(Sub,Suffix).

  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. 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).

  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 Examine the same piece of code with added cuts and look how the cuts affect backtracking

  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). f(3). ?- p(X). ?- a(X). ?- b(X),c(X),d(X),e(X). ?- f(X). X=1 X=1 X=3 X=2 ?- c(1),d(1),e(1). ?- c(2),d(2),e(2). ?- d(1), e(1). ?- d(2), e(2). ?- p(X). X=1; X=2; X=3; no † ?- e(2).

  37. The Cut: cut 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). f(3). ?- p(X). X ?- a(X). ?- b(X),c(X),!,d(X),e(X). X=1 X X=1 ?- c(1), !, d(1), e(1). ?- p(X). X=1; ?- !, d(1), e(1). ?- d(1), e(1).

  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). 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. max(X,Y,Y):- X =< Y, !. max(X,Y,X):- X>Y.

  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: 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,Y):- X =< Y, !. max(X,Y,X):- X>Y.

  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! The combination of cut and fail allows us to code exceptions for our rules.

  41. Exceptions An example: enjoys(vincent,X):- bigKahunaBurger(X), !, fail. enjoys(vincent,X):- burger(X). burger(X):- bigMac(X). burger(X):- bigKahunaBurger(X). burger(X):- whopper(X). bigMac(a). bigKahunaBurger(b). bigMac(c). whopper(d). ?- enjoys(vincent,b). no

  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 does not succeed. cut blocks backtracking and then fail tries to force it. In standard Prolog the prefix operator \+ means negation as failure neg(Goal):- Goal, !, fail. neg(Goal). enjoys(vincent,X):- burger(X), \+ bigKahunaBurger(X).

  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: Negation as failure is not logical negation! enjoys(vincent,X):- \+ bigKahunaBurger(X), burger(X). ?- enjoys(vincent,X). no

  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 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.

  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. Showed how exception are realized in Prolog and why they shouldn’t be thought of as a logical negation. Questions?

More Related