The past few days I have been solving problems at this site called Project Euler. This site contains many seemingly simple math programming problems. I have been using Haskell to solve the problems on the site and in order to help solve one of the problems I wrote this bit of code to generate palindromes.

1: palindrome :: (Integral a) => a -> [Char] -> [String]

` 2: palindrome n al = concat $ map (pal n) al`

` 3: where `

4: pal :: (Integral a)=> a -> Char -> [String]

` 5: pal n x `

6: | n > 2 = map (surround x) (palindrome (n-2) al)

7: | n > 1 = [[x,x]]

` 8: | otherwise = [[x]]`

` 9: where `

10: surround :: Char -> String -> String

` 11: surround lt str = [lt] ++ str ++ [lt]`

This code take a length(as an integer) and a list of characters and returns all possible palindromes that can be created. For example:

palindrome 3 [‘a’..’f’]

will result in

[“aaa”,”aba”,”aca”,”ada”,”aea”,”afa”,”bab”,”bbb”,”bcb”,”bdb”,

“beb”,”bfb”,”cac”,”cbc”,”ccc”,”cdc”,”cec”,”cfc”,”dad”,”dbd”,

“dcd”,”ddd”,”ded”,”dfd”,”eae”,”ebe”,”ece”,”ede”,”eee”,

“efe”,”faf”,”fbf”,”fcf”,”fdf”,”fef”,”fff”]

While I doubt this is the greatest implementation of a method which generates palindromes, it was the first one I came up with and I am curious if anyone can do it in a very different (or *better*) way. So, if anyone reading this wants to show me a different way (in any language) feel free.