Fruitbox

Apr 15, 2008

A simple palindrome generator in Prolog

Filed under: Technology, English

In Prolog, it is very easy to make a predicate that tests whether a string/list of given length is a palindrome, and thus, since we’re talking Prolog, this predicate can be used to generate all palindromes of a given length!
I wrote this in SWI-Prolog, and it depends on the lists library.
Call pal(Alphabet, Length, L), where A is a list of allowed symbols (the alphabet being the most obvious one), Length is the length of the palindrome and L is a palindrome fulfilling the constraints.
The idea is the following: For L to be a correct palindrome, we first check that L has length S, then we say that each element (letter) has to belong to the alphabet A, and finally we state the fact that reversing L will yield L itself, simple enough.

:- use_module(library(lists)).

pal(A, S, L) :-
    length(L, S),
    maplist(mymember(A), L),
    reverse(L, L).

mymember(A, E) :- member(E, A).

The predicate mymember is used so that maplist works the way it should.






















Fruitbox One Million Blogs . org Blog Directory & Search engine
Chat with me by Live Messenger:

Daniel Innala Ahlmark

Get free blog up and running in minutes with Blogsome
Theme designed by Riosoft