22
B. Ross Cosc 4f79 1 Various Prolog tricks nd fast append, etc ktracking can slow down execution significantly. This is not good wh backtracking being done is not useful (ie. you've written a declara gram, but you don't want to put in lots of cuts). common source of this kind of inefficiency is the use of the standa ber, append, and other list processing predicates. often needs nondeterministic append (multi-mode, multiple solutions ell as a deterministic, faster version. ([], X, X). ([A|X], Y, [A|Z]) :- append(X, Y, Z). D([], X, X) :- !. D([A|X], Y, [A|Z]) :- appendD(X, Y, Z), !. ere are as many different logic programming techniques. languages, a plications as there are academics wearing socks with sandals.

Various Prolog tricks

  • Upload
    chul

  • View
    33

  • Download
    2

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Various Prolog tricks

B. Ross Cosc 4f79 1

Various Prolog tricks

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

• There are as many different logic programming techniques. languages, and applications as there are academics wearing socks with sandals.

Page 2: Various Prolog tricks

B. Ross Cosc 4f79 2

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

Page 3: Various Prolog tricks

B. Ross Cosc 4f79 3

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

Page 4: Various Prolog tricks

B. Ross Cosc 4f79 4

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

Page 5: Various Prolog tricks

B. Ross Cosc 4f79 5

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!

Page 6: Various Prolog tricks

B. Ross Cosc 4f79 6

Misc topicsNondeterminism 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

Page 7: Various Prolog tricks

B. Ross Cosc 4f79 7

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

a

b c

tree(a, tree(b, leaf, leaf), tree(c, leaf, leaf))

tree(Value, LeftBranch, RightBranch)

• other data structures similarly modelled.

• big advantage: they are abstract symbolic data structures, which conceptually map to specification quite nicely

Page 8: Various Prolog tricks

B. Ross Cosc 4f79 8

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

Page 9: Various Prolog tricks

B. Ross Cosc 4f79 9

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

Page 10: Various Prolog tricks

B. Ross Cosc 4f79 10

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

Page 11: Various Prolog tricks

B. Ross Cosc 4f79 11

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

Page 12: Various Prolog tricks

B. Ross Cosc 4f79 12

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

Page 13: Various Prolog tricks

B. Ross Cosc 4f79 13

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.

Page 14: Various Prolog tricks

B. Ross Cosc 4f79 14

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

Page 15: Various Prolog tricks

B. Ross Cosc 4f79 15

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.

Page 16: Various Prolog tricks

B. Ross Cosc 4f79 16

Misc topics

• a number of concurrent l.p. languages have been developed

• form of program statements:

H :- G1,...,Gk | B1,...,Bn.

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

commit

Page 17: Various Prolog tricks

B. Ross Cosc 4f79 17

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

Page 18: Various Prolog tricks

B. Ross Cosc 4f79 18

Misc topics

p. 146 Shapiro

Page 19: Various Prolog tricks

B. Ross Cosc 4f79 19

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.

Page 20: Various Prolog tricks

B. Ross Cosc 4f79 20

Misc topics

Natural Language Processing

(p.70 Sicstus)

Page 21: Various Prolog tricks

B. Ross Cosc 4f79 21

Misc topics

Some areas of logic programming research which will affect expertsystem 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)

?

Page 22: Various Prolog tricks

B. Ross Cosc 4f79 22

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)

• ...