Search code examples
listprologreversepalindrome

Code for Prolog program to check whether a given list is palindrome or not without using a reverse operation


This is how to get palindrome using a reverse operation.

predicates

palin(list)
findrev(list,list,list)
compare(list,list)

clauses

palin(List1):-
    findrev(List1,[],List2),
    compare(List1,List2).

findrev([],List1,List1).

findrev([X|Tail],List1,List2):-
    findrev(Tail,[X|List1],List2).

compare([],[]):-
    write("\nList is Palindrome").

compare([X|List1],[X|List2]):-
    compare(List1,List2).    

compare([X|List1],[Y|List2]):-
    write("\nList is not Palindrome").

But I want to do it without reverse operation. Can somebody please help me.


Solution

  • Why not

    pal([]).
    pal([_]).
    pal(Pal) :-
        append([H|T], [H], Pal),
        pal(T).