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.

2 Kommentarer »

URI för TrackBack: http://fruitbox.blogsome.com/2008/04/15/a-simple-palindrome-generator-in-prolog/trackback/

  1. 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

  2. Thanks for that tip. The more efficient, the better!

    Comment av Daniel — Apr 15, 2008 kl. 19:18

RSS för kommentarer på detta inlägg.

Lämna en kommentar

E-postadressen visas aldrig, HTML-kod som är tillåten: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>























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