Saturday, April 18, 2009

Haskell minimum palindrome (response to Prof. Frens)

I took a short break this afternoon from work that's actually due in order to revisit Haskell, a functional programming language I adore but haven't had much chance to use since my first, childish steps in it. Prof. Frens posted an interesting looking problem on his blog, so I thought I'd try it out. The general form of the solution came pretty quickly, but I wound up fighting with Haskell syntax for a good long while, anyway. Need to remember to wrap up those function calls in parenthesis when giving them as arguments >_<. Anyway, here's my solution.


make_palindrome list = list ++ (generate_suffix list [])

generate_suffix sublist current_suffix =
if sublist == reverse(sublist)
then current_suffix
else generate_suffix (tail sublist) (head(sublist):current_suffix)


Not sure if it's the most Haskell-y way to do it, but it's nice and tiny and recursive, which is all I was looking for.

No comments: