next up previous
Next: Knight Tour Up: EXAMPLES Previous: EXAMPLES

List Reverse

Resources can be used as ``slots'' to pass parameter values and results.

The following program (list reverse) uses the resource formula result(Zs) to return the result from the deepest recursive call of rev. For example, by the goal reverse([1,2,3],Zs), the slot result(Zs) is added as a resource and the subgoal rev([1,2,3],[]) is called. At the third recursive call rev([],[3,2,1]), the resource result(Zs) is consumed and the Zs is unified with [3,2,1].

reverse(Xs, Zs) :- result(Zs) -<> rev(Xs, []).
  rev([], Zs) :- result(Zs).
  rev([X|Xs], Zs) :- rev(Xs, [X|Zs]).

The same technique can be used to describe ``accumulators''. For example, a program calculating the summation of a given list can be written as follows.

sum(List, Sum) :- result(Sum) -<> s(List, 0).
  s([], S) :- result(S).
  s([X|Xs], S0) :- S is X+S0, s(Xs, S).

Naoyuki Tamura
Thu May 8 20:39:01 JST 1997