Search code examples
prologpalindrome

Determining if a sentence is a palindrome in prolog


I am trying to write a program to determine if a sentence is a palindrome. This is what I have so far:

palindrome :- write('Sentence: '),
    read(Word),
    name(Word,List),
    palCheck(List).

palCheck(List) :- reverse(List,List).

reverse(L1,L2) :- rev(L1,[],L2).
rev([],L,L).
rev([H|L],L2,L3) :- rev(L,[H|L2],L3).

The problem I have is when I get to a space or an uppercase letter. What I ultimately want is to be able to write DoD dod and get it to pass. I have tried using downcase_atom(X,Y), but having trouble using it as the sentence is something other than an atom.


Solution

  • read/1 acts in a peculiar way: it's a very powerful primitive, able to fully parse Prolog syntax. But the space make the input ill formed. Then surround the literal with quotes, or use some other input primitive: see your Prolog manual!

    ?- palindrome('DoD DoD').
    

    In SWI-Prolog, this query does the check:

    ?- current_stream(_,read,S), read_line_to_codes(S,Cs), maplist(to_lower,Cs,Ls), reverse(Ls,Ls).
    |: AbcCBA
    S = <stream>(0x7fae7b1088e0),
    Cs = [65, 98, 99, 67, 66, 65],
    Ls = [97, 98, 99, 99, 98, 97] .