Recursive Prolog predicate for reverse / palindrome

前端 未结 4 2097
北荒
北荒 2020-12-03 21:59
  1. Can I get a recursive Prolog predicate having two arguments, called reverse, which returns the inverse of a list:

    Sample query and expected result:

4条回答
  •  情歌与酒
    2020-12-03 22:47

    There isn't an efficient way to define reverse/2 with a single recursive definition without using some auxiliary predicate. However, if this is nevertheless permitted, a simple solution which doesn't rely on any built-ins like append/3 (and should be applicable for most Prolog implementations) would be to use an accumulator list, as follows:

    rev([],[]).
    rev([X|Xs], R) :-
        rev_acc(Xs, [X], R).
    
    rev_acc([], R, R).
    rev_acc([X|Xs], Acc, R) :-
        rev_acc(Xs, [X|Acc], R).
    

    rev/2 is the reversal predicate which simply 'delegates' to (or, wraps) the accumulator-based version called rev-acc/2, which recursively adds elements of the input list into an accumulator in reverse order.

    Running this:

    ?- rev([1,3,2,x,4],L).
    L = [4, x, 2, 3, 1].
    

    And indeed as @false has already pointed out (+1),

    palindrome(X) :- rev(X,X). 
    

提交回复
热议问题