Can I get a recursive Prolog predicate having two arguments, called reverse, which returns the inverse of a list:
Sample query and expected result:
?- reverse([a,b,c], L). L = [c,b,a].
A recursive Prolog predicate of two arguments called palindrome
which returns true if the given list is palindrome.
Sample query with expected result:
?- palindrome([a,b,c]). false. ?- palindrome([b,a,c,a,b]). true.
Just for curiosity here goes a recursive implementation of reverse/2 that does not use auxiliary predicates and still reverses the list. You might consider it cheating as it uses reverse/2 using lists and the structure -/2 as arguments.
reverse([], []):-!.
reverse([], R-R).
reverse(R-[], R):-!.
reverse(R-NR, R-NR).
reverse([Head|Tail], Reversed):-
reverse(Tail, R-[Head|NR]),
reverse(R-NR, Reversed).
Ad 1: It is impossible to define reverse/2
as a (directly edit thx to @repeat: tail) recursive predicate - unless you permit an auxiliary predicate.
Ad 2:
palindrome(X) :- reverse(X,X).
But the easiest way is to define such predicates with DCGs:
iseq([]) --> [].
iseq([E|Es]) --> iseq(Es), [E].
reverse(Xs, Ys) :-
phrase(iseq(Xs), Ys).
palindrome(Xs) :-
phrase(palindrome, Xs).
palindrome --> [].
palindrome --> [E].
palindrome --> [E], palindrome, [E].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With