The following Prolog program defines a predicate rev/2
for reversing a list passed in first argument which results in the list passed in second argument:
rev([], []).
rev([XH|XT], Y) :-
rev(XT, Z),
append(Z, [XH], Y).
append([], Y, Y).
append([XH|XT], Y, [XH|ZT]) :-
append(XT, Y, ZT).
The following Prolog program is an alternative implementation of rev/2
:
rev(X, Y) :-
revappend(X, [], Y).
revappend([], Y, Y).
revappend([XH|XT], Y, Z) :-
revappend(XT, [XH|Y], Z).
Both programs work as expected for queries in this argument mode:
?- rev([a, b, c], Y).
Y = [c, b, a]
; false.
But both programs exhaust resources for queries in this argument mode:
?- rev(X, [a, b, c]).
X = [c, b, a]
;
Time limit exceeded
Questions:
- How to fix both programs?
- Are both programs equivalent?