220 likes | 337 Views
Various Prolog tricks. • There are as many different logic programming techniques. languages, and applications as there are academics wearing socks with sandals. Slow and fast append, etc • Backtracking can slow down execution significantly. This is not good when
E N D
Various Prolog tricks • There are as many different logic programming techniques. languages, and applications as there are academics wearing socks with sandals. Slow and fast append, etc • Backtracking can slow down execution significantly. This is not good when the backtracking being done is not useful (ie. you've written a declarative program, but you don't want to put in lots of cuts). - One common source of this kind of inefficiency is the use of the standard member, append, and other list processing predicates. - One often needs nondeterministic append (multi-mode, multiple solutions) as well as a deterministic, faster version. append([], X, X). append([A|X], Y, [A|Z]) :- append(X, Y, Z). appendD([], X, X) :- !. appendD([A|X], Y, [A|Z]) :- appendD(X, Y, Z), !.
Misc topics append is all-powerful. Worship append. • search a list for an element, remove that element from the list... extract( Item, List, NewList) :- append(X, [Item|Y], List), append(X, Y, NewList). (repeated calls to extract remove successive elements) • Get last element from a non-empty list: last(Item, List) :- append(_, [Item], List). • permute a list (shuffle it) shuffle([], []). shuffle(L, [H|T]) :- append(V, [H|U], L), append(V, U, W), shuffle(W, T).
Misc topics • state flags permit precise control of clauses in a predicate, and act like a case statement g_l_p(_, [ ], [ ]) :- !. g_l_p(ascending, List, NewList) :- sort(List, NewList). g_l_p(descending, List, NewList) :- sort(List, Temp), reverse(Temp, NewList). g_l_p(either_sort, List, NewList) :- member(Type, [ascending, descending]), g_l_p(Type, List, NewList). g_l_p(shuffle, List, NewList) :- shuffle(List, NewList). g_l_p(double, List, NewList) :- append(List, List, newList).
Misc topics Iterative vs recursive programs reverse([ ], [ ]). reverse([A|X], Y) :- reverse(X, Z), append(Z, [A], Y). ?- reverse([a,b,c,d], Z), the computation state eventually becomes... ?- reverse([ ], Z4), append(Z4, [d], Z3), append(Z3, [c], Z2), append(Z2, [b], Z1), append(Z1, [a], Z). (inefficient) Better iterative program... reverse(X,Y) :- reverse2([ ], X, Y). reverse2(Y, [ ], Y). reverse2(X1, [U|X2], Y) :- reverse2([U|X1], X2, Y).
Misc topics Nondeterminism vs determinism • nondeterminism means that a program computes more than one solution. • In Prolog, this is reflected by using ";" at the interpreter prompt. Each ";" is like another execution of program. • Nondeterminism results when more than one clause for a predicate can return a solution. This in turn occurs through backtracking. • Declarative Prolog programs are by definition nondeterministic: each clause is a statement of fact, and therefore might return a solution. Thus, a nondeterministic predicate will always let backtracking occur throughout it's clauses. • Unfortunately, this can be computationally expensive, especially when we already know that only one solution is possible!
Misc topics Nondeterminism vs determinism • Better Prolog interpreters will check if nondeterministic predicates can be compiled into deterministic ones. Otherwise, the programmer must do the conversion. p. 86-87 Hogger
Misc topics Data structures • You've used lists and constants. is_a_tree(leaf) . is_a_tree(tree(Val, X, Y)) :- is_a_tree(X), is_a_tree(Y). tree(Value, LeftBranch, RightBranch) a tree(a, tree(b, leaf, leaf), tree(c, leaf, leaf)) b c • other data structures similarly modelled. • big advantage: they are abstract symbolic data structures, which conceptually map to specification quite nicely
Misc topics i) All solutions • When you would like every solution to be returned by a predicate, but you don't want to use ";" at prompt, collect solutions in a loop, or use assert. setof(Template, Goal, Set): Template - structure with variables in Goal that you want to collect Goal - the predicate to execute Set - List to collect solutions into - setof returns executes Goal exhaustively for all the variables in Template, putting the solutions (ordered) in Set
Misc Topics (i) All solutions (cont) eg. likes(bill, cider). likes(dick, beer). likes(harry, beer). likes(jan, cider). likes(tom, beer). likes(tom, cider). ?- setof(X, likes(X, cider), S). S = [bill, jan, tom]. ?- setof((X,Y), likes(X,Y), S). S = [(bill, cider), (dick, beer), .... ]. • Also: bagof(Template, Goal, Bag) - like setof, except that Bag is unordered, and contains no duplicates
Misc topics (ii) Coroutining (Sicstus technique) • The left-to-right depth-first control of standard Prolog is restrictive in writing declarative programs. • Coroutining permits more complex control to be used. However, one pitfall is that debugging becomes more difficult! • Block declaration: ?- block pred(?,?,-,-,?), pred(?,-),.... . ? - must be instantiated - - uninstantiated, blocks while all '-' are uninstantiated in one pattern % merge 2 ordered lists of integers... :- block merge(-, ?, -), merge(?, -, -). merge([], Y, Y). merge(X, [], X). merge([H|X], [E|Y], [H|Z]) :- H < E, merge(X, [E|Y], Z). merge([H|X], [E|Y], [E|Z]) :- H >= E, merge([H|Z], Y, Z). • merge will suspend when args 1 and 3, or args 2 and 3, are uninstantiated
Misc topics • You can then call merge without regard to whether its lists are instantiated or not... ?- merge(X,Y,M), sort([5,2,4,3], X), sort([6,3,7,9], Y). • merge will suspend until both X and Y have values. This means that goal and clause order can be (somewhat) ignored with respect to merge. This in turn permits more declarative programs. • Possible to write recursive predicates which continuall awaken and suspend as their arguments become instantiated. • If blocked goals never awake: system says they are "floundering" • some other coroutining builtin's: when(Condition, Goal) - blocks Goal until Condition satisfied eg. ?- when(X==Y, p(X,Y,T)). freeze(?X, Goal) - blocks Goal until variable X is instantiated
Misc topics (iii) Constraint logic programming • Note that Prolog does not have much intelligence about how to reason about numbers, other than do simple calculations. • One could program complicated predicates with more sophisticated mathematical intelligence; however, this is unreasonable when one wants to apply mathematics to solve problems. • Constraint logic programming: a new field is introduced to predicates, which contains equations of a (mathematical) domain. • The logic program interpreter is supplemented with a constraint solver, which contains algorithmic methods for deriving restuls for this domain. • Then, constraint equations are continually updated during standrd logic program execution. This permits: a) equational results to be output at end of inference b) more sophisticated control of the inference
Misc topics • eg. CLP(R) - A public domain constraint logic programming language - arithmetic constraints: = >= <= > < functor constraint: = eg. fib(0, 1). fib(1, 1). fib(N, X1 + X2) :- N > 1, fib(N - 1, X1), fib(N - 2, X2). ?- fib(10, Z). Z = 34. ?- fib(N, 89). N = 12. • Note: (a) arithmetic done in arguments, (b) test ">" is handled when N is uninstantiated.
Misc topics • CLP(R) (cont) eg. mortgate(P, Time, IntRate, Bal, MP) :- Time > 0, Time <= 1, Bal = P * (1 + Time * IntRate/1200) - Time * MP. mortgage(P, Time, IntRate, Bal, MP) :- Time > 1, mortgage(P*(1 + IntRate/1200) - MP, Time-1, IntRate, Bal, MP). ?- mortgage(100000, 180, 12, 0, MP). MP = 1200.17 ?- mortgage(P, 180, 12, Bal, MP). P = 0.166783 * Bal + 83.3217 * MP • Note: equation used by constraint solver is given as a result
Misc topics ( iv) Concurrent and Parallel Prolog • With ongoing development of multiprocessor computers, one crucial factor is the availability of usable programming languages to exploit these machines. • Logic programming languages are ideally suited for parallel execution. ---> Executing clauses in parallel (OR parallelism) ----> Executing clauses in parallel ( AND parallelism) • "parallel logic programming": exploiting full parallelism with a pure logic program "concurrent logic programming": restricting the parallelism of the logic program program, usually with variable markings, unification rules, and special goals.
Misc topics • a number of concurrent l.p. languages have been developed • form of program statements: H :- G1,...,Gk | B1,...,Bn. commit guard Body H1 :- G1, G2 | A, B, C. H2 :- G3, G4 | D, E. H3 :- G5 | F. • All the clauses are executed in parallel. The guard goals in each are also excecuted in parallel. The first clause whose guard totally succeeds is then used, it's body is executed (in parallel) and the other clauses are killed. • Thus the guard acts much like the "cut". It reduces the amount of parallelism that can occur (else too much parallelism).
Misc topics • Newer concurrent LP languages have "flat" guards, which means that the guard goals must be system predicates (relational ops, unification, etc) • Some languages have rules for unification, for example: - unifying the head should not unify variables not defined in that clause - execution of the guard should not unify variables in the Head
Misc topics p. 146 Shapiro
Misc topics Natural language processing • Prolog is well suited for implementing natural language parsers • Sicstus and others have built-in utilities for implementing definite clause grammars p(X) --> q(X). translates to p(X, S0, S) :- q(X, S0, S). where S0 , S represents list of tokens to process. • You can enclose Prolog code in the grammar rules using {braces}. • AI research into NLU often uses Prolog as an implementation language because complex NL rules can be encoded as declarative logic program components. They incorporate with the above DCG grammar very nicely.
Misc topics Natural Language Processing (p.70 Sicstus)
Misc topics Some areas of logic programming research which will affect expert system technology • language design: - making languages more logical - creating more powerful inference engines (theorem provers) • programming environments - smarter program debuggers - graphical interfaces • language implementation - efficient implmentations (especially parallel ones!) • automatic program verification, synthesis, transformation Expert knowledge (high-level specification) ? Executable rules (program)
Misc topics AI and expert systems research areas... • knowledge representation • AI problem solving (theorem proving) • knowledge acquisition • uncertainty • machine learning • cognitive science (cognitive modelling of expert thinking) • ...