Presentation is loading. Please wait.

Presentation is loading. Please wait.

Agile Software Development Lab Dr. Günter Kniesel, Daniel Speicher, Tobias Rho Spring 2008 Prolog - Part 2 Patrick Rypalla Alexis Raptarchis

Similar presentations


Presentation on theme: "Agile Software Development Lab Dr. Günter Kniesel, Daniel Speicher, Tobias Rho Spring 2008 Prolog - Part 2 Patrick Rypalla Alexis Raptarchis"— Presentation transcript:

1 Agile Software Development Lab Dr. Günter Kniesel, Daniel Speicher, Tobias Rho Spring 2008 Prolog - Part 2 Patrick Rypalla Alexis Raptarchis rypalla@cs.uni-bonn.de raptarch@cs.uni-bonn.de

2 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques2 Lists l A list is a finite sequence of elements. l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques3 Lists: Head and Tail l A non-empty list consists of two parts: uThe head: èThe head is the first element of the list. uThe tail: èThe tail is what remains once we have removed the head. èThe tail of a list is always a list. l What about the empty list? uThe empty list has neither a head nor a tail èPlays an important role in recursive predicates for list processing.

4 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques4 Lists: Head and Tail l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques5 Lists: The Operator | l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques6 Lists: The Operator | l The built-in Prolog operator | is used to decompose a list into its head and tail: ?- [X|Y] = [ ]. no ?-

7 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques7 Lists: The Operator | l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques8 Lists: The Operator | l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques9 Lists: The Anonymous Variable _ l The anonymous variable is used when you need to use a variable, but you are not interested in what Prolog instantiates it to. l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques10 Lists: member/2 l One of the most basic things we would like to know is whether a term X is an element of list L. 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 l doing something to the head, and then l recursively doing the same thing to the tail. èVery important Prolog technique member(X,[X|T]). member(X,[H|T]):- member(X,T).

11 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques11 Lists: member/2 l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques12 Lists: member/2 l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques13 Lists: Excercise l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques14 Lists: Excercise l Solution: l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques15 Arithmetic in Prolog l Prolog offers a number of basic arithmetic tools: 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). ArithmeticProlog ?- 10 is 5+5. yes ?- 4 is 2+3. no

16 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques16 Arithmetic in Prolog l It is important to know that +, -, / and  do not, on their own, carry out any arithmetic. l Expressions such as 3+2, 4-7, 5/5 are ordinary Prolog terms just used in user friendly notation. uFunctor: +, -, /,  uArity: 2 uArguments: integers l This leads to: ?- X = 3 + 2. X = 3+2 yes ?- 3 + 2 = X. X = 3+2 yes

17 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques17 Arithmetic in Prolog: The is/2 predicate l Toforce Prolog to actually evaluate arithmetic expressions, we have to use the is predicate. l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques18 Arithmetic in Prolog: Restrictions of the is/2 predicate 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 term. 3. This Prolog term must be an arithmetic expression.

19 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques19 Arithmetic in Prolog: Arithmetic and Lists l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques20 Accumulator l There is another way of finding out the length of a list using an accumulator: uAccumulators are variables that hold intermediate results. l 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

21 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques21 Accumulator l The accumulator of acclen/3: uInitial value of the accumulator is 0 uAdd 1 to accumulator each time we can recursively take the head of a list uWhen 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques22 Tail-Recursive l Which predicate is better? èacclen/3 because it is tail-recursive. l Difference between tail recursive and recursive: uIn tail recursive predicates the results is fully calculated once we reach the base clause. uIn recursive predicates that are not tail recursive, there are still goals on the stack when we reach the base clause.

23 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques23 Non Tail-Recursive len/2 l Search tree for len/2: ?- 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 len([],0). len([_|L],NewLength):- len(L,Length), NewLength is Length + 1.

24 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques24 Tail-Recursive acclen/3 l Search tree for acclen/2: ?- acclen([a,b,c],0,Len). / \ no ?- acclen([b,c],1,Len). / \ no ?- acclen([c],2,Len). / \ no ?- acclen([],3,Len). / \ Len=3 no acclen([ ],Acc,Acc). acclen([_|L],OldAcc,Length):- NewAcc is OldAcc + 1, acclen(L,NewAcc,Length).

25 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques25 Arithmetic in Prolog: Comparing Integers l Operators that compare integers actually do carry out arithmetic by themselves: l These have the obvious meaning. l Force both left and right hand argument to be evaluated. x < y x  y x = y x  y x  y x > y X < Y X =< Y X =:= Y X =\= Y X >= Y X > Y ArithmeticProlog

26 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques26 Arithmetic in Prolog: Comparing Integers l Some examples: ?- 2 < 4+1. yes ?- 4+3 > 5+5. no ?- 4 = 4. yes ?- 2+2 = 4. no ?- 2+2 =:= 4. yes

27 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques27 Arithmetic in Prolog: Exercise l Define a predicate accMax/3 that takes three arguments, and is true when: uThe first argument is a list of positive integers and uThe 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques28 Arithmetic In Prolog: Excercise l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques29 Other useful predicates for lists: append/3 l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques30 Other useful predicates for lists: append/3 l 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. l How about suffix/2? prefix(P,L):- append(P,_,L). suffix(S,L):- append(_,S,L).

31 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques31 Other useful predicates for lists: Naïve reverse l 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]. unaiveReverse/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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques32 Other useful predicates for lists: reverse l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques33 Other useful predicates for lists: Exercise l Define a predicate sublist/2 that finds sub-lists of lists. èHint: Use already known predicates. l Solution: uThe sub-lists of a list L are simply the prefixes of suffixes of L sublist(Sub,List):- suffix(Suffix,List), prefix(Sub,Suffix).

34 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques34 The Cut l Backtracking is a characteristic feature of Prolog but can often lead to inefficiency èProlog can waste time exploring possibilities that go nowhere. l The cut predicate !/0 offers a way to control backtracking. l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques35 The Cut l In order to better explain the cut, we will uLook at a piece of cut-free Prolog code and see what it does in terms of backtracking uAdd cuts to this Prolog code uExamine the same piece of code with added cuts and look how the cuts affect backtracking

36 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques36 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). X=1; X=2; X=3; no ?- p(X). ?- a(X).?- f(X). ?- d(2), e(2). ?- e(2). ?- d(1), e(1). ?- c(1),d(1),e(1).?- c(2),d(2),e(2). ?- b(X),c(X),d(X),e(X). X=1 X=2 † X=3

37 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques37 The Cut: cut ?- p(X). X=1; ?- p(X). ?- a(X).?- b(X),c(X),!,d(X),e(X). X=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). f(3). ?- c(1), !, d(1), e(1). X=1 ?- !, d(1), e(1). ?- d(1), e(1). X X

38 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques38 The Cut l 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! l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques39 Green Cuts, Red Cuts l Cuts that do not change the meaning of a predicate are called green cuts. l 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 l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques40 The fail/0 predicate l fail/0 is a special predicate that will immediately fail when Prolog encounters it as a goal. l May not sound too useful but: When Prolog fails, it tries to backtrack! l The combination of cut and fail allows us to code exceptions for our rules.

41 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques41 Exceptions l 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 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques42 Negation as failure l 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. l In standard Prolog the prefix operator \+ means negation as failure neg(Goal):- Goal, !, fail. neg(Goal). enjoys(vincent,X):- burger(X), \+ bigKahunaBurger(X).

43 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques43 Negation As Failure: Excercise l What would happen if we changed the order of the goals in the burger example? That is if we had: l Solution: èNegation as failure is not logical negation! enjoys(vincent,X):- \+ bigKahunaBurger(X), burger(X). ?- enjoys(vincent,X). no

44 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques44 Meta-Predicates l Meta-predicates are used to match, query, and manipulate other predicates in the problem domain. l 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 l Through meta-predicates Prolog can analyze, transform, and simulate other programs. l It can even learn not only new data knowledge, but new procedural knowledge.

45 Agile Software Development Lab, Spring 2008 Prolog: Language and essential logic programming techniques45 Summary l We introduced lists and some recursive predicates that work on lists. èThe kind of programming that these predicates illustrated are fundamental to Prolog. l We introduced the programming technique of using accumulators, which often offer an efficient solution. l Showed how exception are realized in Prolog and why they shouldn’t be thought of as a logical negation. l Questions?


Download ppt "Agile Software Development Lab Dr. Günter Kniesel, Daniel Speicher, Tobias Rho Spring 2008 Prolog - Part 2 Patrick Rypalla Alexis Raptarchis"

Similar presentations


Ads by Google