A simple palindrome generator in Prolog
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.

You can put the reverse/2 goal right after the length/2 goal to make this predicate much more efficient.
Comment av None — Apr 15, 2008 kl. 18:48
Thanks for that tip. The more efficient, the better!
Comment av Daniel — Apr 15, 2008 kl. 19:18
Evil is a deed as I live.
God, am I reviled? I rise, my bed on a sun, I melt.
To be not one man emanating is sad. I piss.
Alas, it is so late. Who stops to help?
Man, it is hot. I’m in it. I tell.
I am not a devil. I level “Mad Dog”.
Ah, say burning is, as a deified gulp
Comment av Anonymous — Oct 31, 2008 kl. 19:36