15.08.2013 Views

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 638 Computing the the n th Fibonacci Number (0,1,1,2,3,5,8,13,. . . ; add the last<br />

two to get the next), using the addition predicate above.<br />

fib(zero,zero).<br />

fib(s(zero),s(zero)).<br />

fib(s(s(X)),Y):-fib(s(X),Z),fib(X,W),add(Z,W,Y).<br />

Example 639 using ProLog’s internal arithmetic: a goal of the form ?- D\;is\;e. where<br />

e is a ground arithmetic expression binds D to the result of evaluating e.<br />

fib(0,0).<br />

fib(1,1).<br />

fib(X,Y):- D is X - 1, E is X - 2,fib(D,Z),fib(E,W), Y is Z + W.<br />

c○: Michael Kohlhase 512<br />

Note: Note that the is relation does not allow “generate-and-test” inversion as it insists on the<br />

right hand being ground. In our example above, this is not a problem, if we call the fib with<br />

the first (“input”) argument a ground term. Indeed, if match the last rule with a goal ?- g,Y.,<br />

where g is a ground term, then g-1 and g-2 are ground and thus D and E are bound to the<br />

(ground) result terms. This makes the input arguments in the two recursive calls ground, and<br />

we get ground results for Z and W, which allows the last goal to succeed with a ground result for<br />

Y. Note as well that re-ordering the body literals of the rule so that the recursive calls are called<br />

before the computation literals will lead to failure.<br />

Adding Lists to ProLog<br />

Lists are represented by terms of the form [a,b,c,. . .]<br />

first/rest representation [F|R], where R is a rest list.<br />

predicates for member, append and reverse of lists in default ProLog representation.<br />

member(X,[X|_]).<br />

member(X,[_|R]):-member(X,R).<br />

append([],L,L).<br />

append([X|R],L,[X|S]):-append(R,L,S).<br />

reverse([],[]).<br />

reverse([X|R],L):-reverse(R,S),append(S,[X],L).<br />

c○: Michael Kohlhase 513<br />

Relational Programming Techniques<br />

Parameters have no unique direction “in” or “out”<br />

:- rev(L,[1,2,3]).<br />

:- rev([1,2,3],L1).<br />

:- rev([1,X],[2,Y]).<br />

Symbolic programming by structural induction<br />

rev([],[]).<br />

rev([X,Xs],Ys) :- ...<br />

Generate and test<br />

sort(Xs,Ys) :- perm(Xs,Ys), ordered(Ys).<br />

270

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!