Question

I developed a palindrome checking algorithm that simply reverses a given list of elements; using naive reversing. The program then checks if it yields the same list or not. But I seem to have a problem that I can't figure out. The program always return false. Here's the program I've developed so far...

reverseCurrentList([H|T],ReversedList):-
    reverseCurrentList(T,RevT),
    append(RevT,[H],ReversedList).

isPalindrome(GivenList):- 
    reverseCurrentList(GivenList,ReversedList),
    GivenList=@=ReversedList.

Edit: final version

In the end, I settled with the following code:

% A palindrome can be read forward or backward; e.g. [x,a,m,a,x]

% is_palindrome(L) :- L is a palindrome list

is_palindrome(L) :-
   reverse(L,L).
Was it helpful?

Solution

Your reverseCurrentList rule is missing a base clause, so it never succeeds. The recursive invocation continues taking items from the list until the list is empty, at which point [H|T] no longer unifies, so the rule fails.

Add this second clause to your program:

reverseCurrentList([], []).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top