Prolog Coding

download Prolog Coding

of 552

  • date post

  • Category


  • view

  • download


Embed Size (px)

Transcript of Prolog Coding

:-4 Arithmetic andNondeterminismProlog arithmetic can be a little surprising; you need to beaware of modes. Sometimes nondeterminism needs to bemanaged.1. Arithmetic2. Operators3. Modes and Arithmetic4. Expressions5. Managing Nondeterminism6. Arithmetic and Lists85:-4.1 ArithmeticIn most languages 3 + 4 is an expression that has a valueIn Prolog, 3 + 4 is just a term whose functor is + andarguments are 3 and 4Its not code, its dataThe Prolog builtin = just unies (matches) two terms, itdoes not evaluate expressions?- X = 3 + 4.X = 3+4 ;No86:-Arithmetic (2)Use the built in is/2 predicate to compute the value of anarithmetic expression:?- is(X, 3+4).X = 7 ;Nois(X, Y) holds when X is a number and Y is an arithmeticexpression and X is the value of Y87:-4.2 Operatorsis is actually an inx operator in PrologThis means that instead of writing is(X,3+4) we could alsohave written X is 3+4This is easier to read, so it preferred, although both workSimilarly, + is an operator; 3+4 is the same as +(3,4)Operators in Prolog are not exclusively for arithmetic, theyare part of Prologs syntaxProlog has many other standard operators; some we havealready seen, including :- , ; modOperators only aect syntax, not meaningYou can dene your own operators88:-4.2.1 Precedence and AssociativityOperators have precedence and associativityUse parentheses for groupingE.g. * and / have higher precedence than + and -; they allassociate to the left?- X is 3 + 4 * 5, Y is (3 + 4) * 5.X = 23Y = 35Yes?- X is 5 - 3 - 1, Y is 5 - (3 - 1).X = 1Y = 3Yes89:-4.2.2 DisplayThe built-in predicate display/1 is useful for understandinghow your input will be parsed when it includes operatorsdisplay/1 prints a term as Prolog understands it, usingonly the standard form with the functor rst, andarguments between parentheses?- display(3 + 4 * 5), nl, display((3 + 4) * 5).+(3, *(4, 5))*(+(3, 4), 5)Yes?- display(5 - 3 - 1), nl, display(5 - (3 - 1)).-(-(5, 3), 1)-(5, -(3, 1))Yes90:-4.3 Modes and ArithmeticWe could code a predicate to compute a square like this:square(N, N2) :- N2 is N * N.?- square(5, X).X = 25 ;No?- square(X, 25).ERROR: Arguments are not sufficiently instantiatedWe cant use this denition to compute a square root!91:-Modes and Arithmetic (2)Unfortunately, is/2 only works when the second argumentis groundThe rst argument can be unbound or bound to a number?- X is 3 + Y.ERROR: Arguments are not sufficiently instantiated?- 7 is 3 + 4.Yes?- 9 is 3 + 4.No?- 2 + 5 is 3 + 4.No92:-4.4 ExpressionsSome arithmetic expressions understood by is/2:E1 + E2 addition float(E1) oat equivalent of E1E1 - E2 subtraction E1 > E2 right shiftE1 / E2 division E1 /\ E2 bitwise andE1 // E2 integer division E1 \/ E2 bitwise orE1 mod E2 modulo (sign of E1) \ E1 bitwise complement-E1 unary minus min(E1, E2) minimumabs(E1) absolute value max(E1, E2) maximuminteger(E1) truncate toward 093:-Expressions (2)Some useful arithmetic predicates:E1 < E2 less thanE1 =< E2 equal or less Danger : not = E2 greater or equalE1 > E2 greater thanE1 =:= E2 equal (only numbers)E1 =\= E2 not equal (only numbers)All of these take ground arithmetic expressions as botharguments94:-4.5 Managing NondeterminismA common Prolog programming error is treating multipleclauses as if they formed an if-then-else constructThis is an erroneous denition of absolute_value:absolute_value(X, X) :- X >= 0.absolute_value(X, Y) :- Y is -X.?- absolute_value(-3, V).V = 3 ;No?- absolute_value(42, V).V = 42 ;V = -42 ;NoWhy do +ve numbers have two absolute values, one ofthem -ve?95:-Managing Nondeterminism (2)The problem is that the second clause promises that[n[ = nfor any n, regardless of its signThe correct denition:absolute_value(X, X) :- X >= 0.absolute_value(X, Y) :- X < 0, Y is -X.?- absolute_value(-3, V).V = 3 ;No?- absolute_value(42, V).V = 42 ;No96:-ExerciseDene a Prolog predicate maximum(X,Y,Z) such that Z is thelarger of X and Y97:-4.5.1 Fibonacci numbersFibonacci numbers: 1, 1, 2, 3, 5, 8, 13, . . .fib(0, 1).fib(1, 1).fib(N, F) :-N > 1,N1 is N - 1,N2 is N - 2,fib(N1, F1),fib(N2, F2),F is F1 + F2.What if we change the order of goals? What if we do F isF1 + F2 rst?Note: each call makes two recursive calls. Are there betterways to compute Fibonacci numbers?98:-4.6 Lists and ArithmeticSumming a list combines arithmetic with list processing:sumlist([], 0). % sum([]) = 0sumlist([X[Xs], Sum) :- % sum([X[Xs]) = Sum ifsumlist(Xs, Sum1), % sum(Xs) = Sum1 andSum is Sum1 + X. % Sum = Sum1 + XThis can be done more eciently:sumlist([], Sum, Sum). % sum([]) + Sum = Sumsumlist([X[Xs], Sum0, Sum):-% sum([X[Xs]) + Sum0 = Sum ifSum1 is Sum0 + X, % Sum1 = Sum0 + X, andsumlist(Xs, Sum1, Sum).% sum(Xs) + Sum1 = SumSee the lecture on eciency for more on this99:-4.6.1 List MaximumCompute the maximum element of a listmaxlist([X], X).maxlist([X[Xs], Max) :-maxlist(Xs, Max1),maximum(Max1, X, Max).Note: no clause for []! Base case is singleton list because[] has no maximum100:-4.6.2 List LengthThe length/2 built-in relates a list to its length?- length([a,b,c], 3).Yes?- length([a,b,c], N).N = 3 ;No?- length(L, 3).L = [_G263, _G266, _G269] ;No?- length(L, N).L = []N = 0 ;L = [_G278]N = 1YesIt is not straightforward to implement length/2 withexible modes; covered later101:-4.6.3 List HandlingMany other list predicates can be dened using append,length.member/2 could be dened just in terms of append:member(X, L) :- % X is a member of L, if L of formappend(_, [X|_], L). % any list ++ [X] ++ any listE is the Nthelement of list L (counting from 0):element(N, L, E) :- % E is the Nth element of Lappend(F, [E|_], L), % if exists F where L = F ++ [E] ++ anylength(F, N). % and the length of F is N102:-List Handling (2)T is a list taking the rst N elements of L:take(N, L, T) :- % T is the first N elements of Lappend(T, _, L), % if L = T ++ any listlength(T, N). % and the length of T in NT is what is left after removing the rst N elements of L:drop(N, L, T) :- % T is the first N elements of Lappend(F, T, L), % if L = T ++ any listlength(F, N). % and the length of T in NL is a list all of whose elements are E:listof([], _). % [] is a list of anythinglistof([E|Es], E) :- % [E|Es] is a list of Es iflistof(Es, E). % Es is103104105106107108:-5 Coding in PrologWe work through examples to illustrate how to writeProlog codeOur goal: support code for a computerized card game1. Data and Representation2. Generating a deck of cards3. Shuing4. Dealing109:-5.1 DataFor any language, rst determine: what data we manipulate, how they are related, what are their attributes, and what are their primitive operationsWe need to represent a (partial) deck of cards, a hand,individual cards, suits, ranksAssume we dont need jokers for this game110:-Data (2)Suits and Ranks have no attributesTheir primitive operations are only distinguishing them andpossibly enumerating themA card comprises a suit and a rank those are itsattributesConstructing a card from rank and suit, and nding acards rank and suit are its only primitive operationsA deck is just an (ordered) sequence of cardsPrimitive operations include removing the top card oradding a card on top; all other operations can beimplemented in terms of those111:-5.2 RepresentationSimplest Prolog representations for types without attributesare atoms and numbers, e.g., hearts, jack, 10, etcGood idea to write a predicate for each type to specifywhat are members of the typeSame code can enumerate valuessuit(clubs). suit(diamonds).suit(hearts). suit(spades).rank(2). rank(3). rank(4).rank(5). rank(6). rank(7).rank(8). rank(9). rank(10).rank(jack). rank(queen).rank(king). rank(ace).112:-Representation (2)Simplest Prolog representation for type with attributes iscompound term, one argument for each attributeFor playing card: card(R, S), where R is a rank and S is asuitcard(card(R,S)) :-suit(S),rank(R).Since rank and suit will enumerate the ranks and suits, thiscode will enumerate the cards of a deck113:-Representation (3)Deck is just a sequence of any number of cardsProlog has good support for lists good representationfor sequencesList is a deck if each element is a card, i.e., if empty, or ifrst element is