1 / 55

LOGIC PROGRAMMING (WEEK 4)

LOGIC PROGRAMMING (WEEK 4). Eleni E. Mangina Department of Computer Science University College Dublin. Equality and unification Arithmetic expressions Terminology Lists Structures. Lecture 10. Terms.

suchin
Télécharger la présentation

LOGIC PROGRAMMING (WEEK 4)

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. LOGIC PROGRAMMING(WEEK 4) Eleni E. Mangina Department of Computer Science University College Dublin • Equality and unification • Arithmetic expressions • Terminology • Lists • Structures DEPT. OF COMPUTER SCIENCE UCD

  2. Lecture 10 DEPT. OF COMPUTER SCIENCE UCD

  3. Terms • So far, we have only encountered predicates which talk about simple values, called atomic constants eg. jane a 1 simple_term • When we want to represent complicated, structured knowledge, this is reather limited • Therefore, we are also allowed to use more general structures called terms DEPT. OF COMPUTER SCIENCE UCD

  4. Terms (2) • A term is like a literal I.e. • It has a functor – a Prolog atom; • And maybe some arguments, each of which can be a term, or a variable • Examples of terms: simple_term dog(bonzo) fat(X) lots(a,2,D,f(X,g)) ‘a string’(‘EVEN capitals!’) • These are not terms: 2(X) X(2) DEPT. OF COMPUTER SCIENCE UCD

  5. Terms (3) • The difference between literals and terms is: • Literals form individual goals to which a truth value can be assigned; • Terms are values in themselves and do not have a truth value. • You can tell the difference by where there are found: • Literals appear as the outermost structure in heads and bodies of clauses and in goals, eg. ?- lit1( t_in_lit1 ), lit2( t_in_lit2 ). • Terms appear as arguments to literals eg. ?- literal( functor( arg1, arg2)). X = 2. DEPT. OF COMPUTER SCIENCE UCD

  6. functor literal arg1 atom arg2 func Terms (4) • We sometimes think of terms as tree structures (Trees in computer science grow downwards!) • So the term functor( arg1, arg2 ) might be thought of as: • And literal( atom, func( 1, 2 )) as: 1 2 DEPT. OF COMPUTER SCIENCE UCD

  7. Terms (5) • Examples of terms: % person( Name, Age, EyeCol, HairCol) person( george, 35, brown, fair). animal( type = dog, name = bonzo, hairyness = very). • While terms are helpful in making the language more flexible, they are still not completely so – the number of arguments is fixed • What happens if we want to represent a variable number of things in one place? DEPT. OF COMPUTER SCIENCE UCD

  8. Unification The “=” sign may seem like an equality test: | ?- 5 = 7. no | ?- 5 = 5. yes | ?- a = b. no Or it may seem like an assignment command: | ?- X = 7. X = 7 ? yes | ?- 7 = Y. Y = 7 ? yes DEPT. OF COMPUTER SCIENCE UCD

  9. The “=” sign indicates unification – what we have been calling “matching”. Two constants unify if and only if they are identical. An unbound variable unifies with anything, and becomesbound to it. Two structures unify if they are the same kind of structure,have the same number of components, and each pair ofcorresponding components unifies; any variables involvedin these unifications will become bound to whatever itunifies with. DEPT. OF COMPUTER SCIENCE UCD

  10. Arithmetic | ?- Num = 5 + 6. Num = 5 + 6 ? yes Arithmetical expressions are not automatically evaluated: They count as structures, and unify accordingly: | ?- X + Y = 5 + 6. X = 5, Y = 6 ? yes | ?- Z + W = a*b + c. W = c, Z = a*b ? yes DEPT. OF COMPUTER SCIENCE UCD

  11. | ?- (3 + 4) * (7 + 9) = (A + 4) * M. A = 3, M = 7+9 ? yes | ?- (3 + 4) * (7 + 9) = (C + D) * (E + F). C = 3, D = 4, E = 7, F = 9 ? DEPT. OF COMPUTER SCIENCE UCD

  12. Evaluating arithmetic expressions The is operator will evaluate arithmetic expressions: | ?- N is 3 +1. N = 4 ? yes | ?- Total is (3 + 4) * (7 + 9). Total = 112 ? yes It uses unification, so the variable does not have to be unbound: | ?- M is 6, M is 3 * 2. M = 6 yes DEPT. OF COMPUTER SCIENCE UCD

  13. | ?- Calculation = (2 * 3) + (5 * 4), Value is Calculation. Value = 26, Calculation = 2*3+5*4 ? yes | ?- Calculation = (2 * 3) + (5 * 4), Value is Calculation + 1. Value = 27, Calculation = 2*3+5*4 ? yes | ?- Calculation = (2 * 3) + (5 * 4), Value = Calculation + 1. Calculation = 2*3+5*4, V = 2*3+5*4+1 ? yes DEPT. OF COMPUTER SCIENCE UCD

  14. This does not work: | ?- N is 24, N is N + 1. This would try to bind N to both 24 and 24 + 1 simultaneously. DEPT. OF COMPUTER SCIENCE UCD

  15. Types of object Also: variables (starting with capitals or with underscore); structures (arithmetic expressions, and others). DEPT. OF COMPUTER SCIENCE UCD

  16. Lists A list is a collection of zero or more data-items, in order: [a] % a list of one element [34, 14, z] % a list of three elements [[a, b, c], Dummy] % a list of two elements, with the first % element being a list of three elements, % and the second element a variable Like any object, a list can be the value of a variable: | ?- [Any, list, of, items] = Avariable. Avariable = [Any,list,of,items] ? yes DEPT. OF COMPUTER SCIENCE UCD

  17. Two lists unify if they are the same length and all theirelements unify: | ?- [a, b, c, d] = [Var1, b, Var2, d]. Var1 = a, Var2 = c ? yes | ?- [1, What, 2, X, 3] = [A, b, C, d, E]. A = 1, C = 2, E = 3, X = d, What = b ? yes DEPT. OF COMPUTER SCIENCE UCD

  18. | ?- [(a + X),(Y + b)] = [(W + c),(d + b)]. W = a, X = c, Y = d ? yes | ?- [[X, a]] = [X,a]. no | ?- [[X, a]] = [[b, Y]]. X = b, Y = a ? yes Note the “unification-inside-unification” – recursion. DEPT. OF COMPUTER SCIENCE UCD

  19. Lecture 11 DEPT. OF COMPUTER SCIENCE UCD

  20. Lists • There is a special kind of term, called a list • It can be represented in 2 ways – the internal representation or the syntactic sugar • The internal representation uses 2 symbols: . (dot – a functor) [ ] (empty list – an atom) • . connects a term (on the left) with a list (on the right) • NB this is not symmetrical • The last list to be connected to any list is [ ] DEPT. OF COMPUTER SCIENCE UCD

  21. Lists (2) • Examples: [ ] .(a,[ ]) .(1,.(2,[ ])) .(.(a, [ ]),.(.(b,.(c,[ ])),[ ])) • However, thisi snot an easy notation • Instead of ., we write [A|B] where A is the term (head) and B is the list (tail) • The same examples: [ ] [a|[ ] ] [1|[2|[ ] ] ] [ [a|[ ] ] | [ [b| [c| [ ] ] | [ ] ] ] ] DEPT. OF COMPUTER SCIENCE UCD

  22. Lists (3) • This is still not easy to read • So we introduce simpler forms [A] [A|[ ] ] [A,B] [A|B|[ ] ] ] [A,B|C] [A| [B|C] ] • Now our examples read: [ ] [a] [1,2] [ [a],[b,c] ] Which is much better! DEPT. OF COMPUTER SCIENCE UCD

  23. Lists (4) • The different forms of list are all interchangeable, so ?- [a,b,c] = .(a,.(b,.(c, [ ]))) yes ?- [1,2] = [1| [2|[ ] ] ] yes • Lists are important because: • They enable us to deal with collections of items • They enable us to control recursive programs DEPT. OF COMPUTER SCIENCE UCD

  24. Definition of a list The empty list, [ ], is a list. Adding an item to the front of an existing list makes alist. So, adding b to [ ] means that [b] is a list. Hence, [a, b] is a list. And so on. Or alternatively: The empty list, [ ], is a list. A structure of the form [X, ...] is a list if X is any item and [...] is a list, possibly empty. So, to ask if [a, b] is a list, we consider whether [b] is a list, and to answer that we ask if [ ] is a list. It is, so the overall answer is that [a, b] is a list. That is, a list is a recursively defined structure. DEPT. OF COMPUTER SCIENCE UCD

  25. Bar notation in lists | ?- [a, b, c, d] = [X|Y]. X = a, Y = [b,c,d] ? yes | ?- [a, b, c, d] = [X|[Z|W]]. W = [c,d], X = a, Z = b ? yes | ?- [a|[b|[c|[ ]]]] = Wholelist. Wholelist = [a,b,c] ? no DEPT. OF COMPUTER SCIENCE UCD

  26. Structures To group a set of items into a structure, use a functor (a constant symbol) with the items as arguments. something(a, b, X, [1,2,3]) Functor is something, there are 4 arguments. Like a “record” in many traditional programming languages. A structure can be the value of a variable: | ?- Theman = person(mike, london, 36). Theman = person(mike, london, 36) ? yes DEPT. OF COMPUTER SCIENCE UCD

  27. Structure Unification Structures can unify, if same functor and same number of arguments, and arguments all unify: | ?- person(Nm, Addr, Age) = person(mike, london, 36). Age = 36, Nm = mike, Addr = london? yes | ?- person(Someone, _ , 45) = person(harry, dundee, 45). Someone = harry? yes (The plain underscore does not receive any bindings.) DEPT. OF COMPUTER SCIENCE UCD

  28. A structure may have another structure as an argument. addr(flat(23), street(140), postcode(2122)) Unification then works in the obvious way, recursively: ?- addr(flat(23),street(140),postcode(2122)) = addr(flat(F), _Str, Code). F = 23, Code = postcode(2122) ? yes ?- addr(flat(23),street(140),postcode(2122)) = addr(postcode(P), _Str, flat(F)). no (Any variable beginning with underscore is not reported bythe interface). DEPT. OF COMPUTER SCIENCE UCD

  29. Arithmetic expressions as structures Arithmetic expressions are structures with +, *, etc. as functors. | ?- +(2, 3) = 2 + 3. yes They can be unified (recursively): | ?- +(2, *(5,6)) = X + 5 * Y. X = 2, Y = 6 ? yes They can be evaluated with is: | ?- Result is +(2, *(5,6)). Result = 32 ? yes DEPT. OF COMPUTER SCIENCE UCD

  30. Lists as structures The special functor “.” holds lists together – a “join to thefront” connector. | ?- .(a, [ ]) = [a]. yes | ?- List = .(a, [ ]) . List = [a] ? yes | ?- .(a, .(b, .(c, []))) = Alist. Alist = [a,b,c] ? yes DEPT. OF COMPUTER SCIENCE UCD

  31. | ?- .(a, .(b, .(c, []))) = [First,b,Last]. Last = c, First = a ? yes | ?- .(a, .(b, .(c, []))) = [a| .(b, [c])]. yes Mixing the various list notations is not recommended. DEPT. OF COMPUTER SCIENCE UCD

  32. functor X a Unification • Now that we have terms, our original idea of unification is not adequate • We need to be able to deal with more complex structures, eg person(Name, Age) = person(george,65) functor(X,a) = functor(Y,Y) [a,f(X,Y)] = [A|[f(A,B)]] • We can think of unification as matching trees: functor Y Y DEPT. OF COMPUTER SCIENCE UCD

  33. First-order term Unification in Prolog • To unify two terms • Compare their functors; if they do not match then fail; otherwise… • If the terms have different numbers of arguments, then fails; otherwise… * • If the terms have no arguments then succeed; otherwise… • For each pair of respective arguments • If one is a variable, let it be identical to the other; otherwise… • Unify the two arguments using this procedure (*) This is an efficiency measure in some systems • A more formal version of this algorithm is given in “Foundations of Logic Programming” (John W. Lloyd, 1987, publ. Springer-Verlag) DEPT. OF COMPUTER SCIENCE UCD

  34. First order term unification (2) • It is important to understand that this algorithm is an approximation • In one particular situation, it is unsound – I.e. logically incorrect • That situation is when a variable is uninfied with a term strictly containing itself eg X = f(X) g(X) = g(p(X,Y)) • In principle, we can test for this (the occurs check) but in practice doing so is too slow • So we ignore it on the basis that such expressions are meaningless anyway and should never arise DEPT. OF COMPUTER SCIENCE UCD

  35. Summary • The “=” symbol indicates unification (matching) • Arithmetic expressions are not automatically evaluated • The “is” operator evaluates arithmetic expressions • A list is an ordered collection of items • A list is made up of a first element and a further list ofitems. • A structure is a general way of clustering data • Arithmetic expressions and lists are specialstructures • All structures unify by unifying their components,recursively. DEPT. OF COMPUTER SCIENCE UCD

  36. Lecture 12 DEPT. OF COMPUTER SCIENCE UCD

  37. Input/Output (IO) • Input/Output is a problem for declarative programming languages • Output: we cannot give a truth value to the action of printing something • Input: we could, maybe, view input as coming from a changing Prolog database, but this still gives us problems in understanding what the program means • The problems get worse when we get on to flexible computation rules, later! • In fact, there are ways to tell a declarative story about I/O, but we will not cover them here DEPT. OF COMPUTER SCIENCE UCD

  38. IO facilities in SICStus Prolog • Two ways of thinking about IO: • File-based • Stream-based • File-based IO is nice and simple, but is not well-thought-out and can be confusing • Stream-based IO is more complicated, but much more reliable • In SICStus, file-based IO is implemented through stream-based IO DEPT. OF COMPUTER SCIENCE UCD

  39. File-based IO in SICStus • File-based IO is based on the idea of a “current file” (which may be the terminal) • You can have severaql files open at once, but you can only read from or write to one at a time • Each file has a pointer, which marks where the last operation took place DEPT. OF COMPUTER SCIENCE UCD

  40. File-based IO in SICStus (2) • We have nine basic predicates: see/1: choose the current reading file (and open it if necessary) seen/0: close the current reading file seeing/1: which is the current reading file? read/1: read a term from the current reading file tell/1: choose the current writing file (and open it if necessary) told/0: close the current writing file telling/1: which is the current writing file? write/1: wrute a term to the current existing file nl/0: write a newline to the current writing file • The terminal is a file called user DEPT. OF COMPUTER SCIENCE UCD

  41. File-based IO in SICStus • Example: | ?- tell(example). yes | ?- write(example(term)), write( ‘.’). yes | ?- told yes | ?- see(example) yes | ?- seeing(example). File = example ? yes | ?- read(Term). Term = example(term)? yes | ?- seen, seeing (File). File = user ? yes DEPT. OF COMPUTER SCIENCE UCD

  42. Stream-based IO in SICStus • We associate each open filewith an explicit pointer with which we refer to it subsequently • There are too many predicates to learn usefully – see manual for details • The basic streamm handling predicates are: open/3 arguments: a file specification (+); a mode(read/write/append) (+); a pointer (-) close/1 argument: a pointer (+) current_input/1 argument: a pointer (?) set_input/1 argument: a pointer(-) read/2 arguments: a pointer (+); a term(?) write/2 arguments: a pointer (+); a term(?) DEPT. OF COMPUTER SCIENCE UCD

  43. General IO in SICStus • Most of the reading and writing predicates come in two versions: • To the current file/stream (eg. Write/1) • To a named stream (eg. Write/2) • The first argument is conventionally the stream pointer DEPT. OF COMPUTER SCIENCE UCD

  44. The format predicate • The most useful writing predicates are format/2 and format/3 • Format/2 has two arguments • A format specification (atom or string) • A list of arguments • For example the predicate call Format (‘v\n~w - ~w+\n’, [term1, term2]). Will print out to the terminal v temr1 – term2+ • See the manual for more details of format specifications DEPT. OF COMPUTER SCIENCE UCD

  45. Arithmetic operators • Recall that =/2 means unify • We need arithmetic functions, even in logic programs • Here are the basic arithmetic predicate is/2 computes the value of the arithmetic expression in its second argument (+) and unifies it with the first argument (?) >= > =:= =\= < =</2 all compute the respective comparison between the values of two arithmetic expressions (+,+) • See the manual for more details DEPT. OF COMPUTER SCIENCE UCD

  46. Meta-Predicates • Meta-predicates are predicates which work on data which is outside the logic of prolog • Usually, they assign truth values to statements about the logic or the language • They are mostly meant for programming where the data is a program…. … but they are often abused to write hacky prolog code DEPT. OF COMPUTER SCIENCE UCD

  47. Meta-Predicates (2) • Example: var/1 • var is a meta-predicate which tests whether or not its argument is a variable • It is a meta-predicate because a variable is not a term – it may contain one, but it is not one… … so this predicate works on part of the external prolog languaage, not on its internal logic • var/1 might be used in an implementation of unification to decide whether a variable had already been unified or not DEPT. OF COMPUTER SCIENCE UCD

  48. Misusing meta-predicates • Here is how NOT to use ground/1, which succeeds if its argument is fully instantiated • We want to test if two expressions are equal: equal (X,Y) :- ground (X), ground (Y), Y =:= X. equal (X,Y) :- ground (X), \+ ground (Y), Y is X. equal (X,Y) :- \+ ground (X), ground (Y), X is Y. equal (X,Y) :- \+ground(X), \+ground(Y), format(‘Error! \n’, [ ]). DEPT. OF COMPUTER SCIENCE UCD

  49. To meta-program or not? • Rule of thumb 1: if you have to use a meta-predicate and you are not sure why, there is something wrong • Rule of thumb 2: if you have to use a meta-predicate and your data is not part of a program clause, there is something wrong • Do not ever use meta-predicates to control the run-time behaviour of Prolog (as in the example), because: • It messes up the logic of your program • It makes your program very hard to analyse automatically • There are much better ways to do it DEPT. OF COMPUTER SCIENCE UCD

  50. Some safe, useful predicates • There are three meta-predicates which are very useful and mostly safe logically • They are concerned with finding multiple solutions to queries • Findall/3 is exactly analogous to running a query and asking for all the solutions by hitting ; at the prompt • For example, given a definition of ancestor/2. Findall(X, ancestor(john, X), Answers) instantiates Answers with a list of all the Xs such that ancestor (john, X) Is provable in the current database DEPT. OF COMPUTER SCIENCE UCD

More Related