02 November 2011

Palindrome in Haskell

This is probably a week after i started to read Haskell (a functional programming language). Having tried few examples from the book and writing few on my own, i feel like it is a different world. If i m successful enough to keep my interest with Haskell and continue to practice, i think it is going to improve my thinking at a very least. I m not so sure of using this language at work (but who knows). More on Haskell later.

Here is the code that says a given String (list) is palindrome. (see, how expressive Haskell (FP) is). The first two line is to reverse the list and the last line is the one that decides whether or not the original and reversed string same (you need to write probably 10 lines in imperative language)

rev [] = [] 
rev (x:xs) = reverse xs ++ [x] 
palindrome x = (x == rev x)
 Here is the sample output (from WinGHCi)


*Main> palindrome "test"
False
*Main> palindrome "madam"
True
*Main> palindrome "123321"
True
*Main> palindrome [1..100]
False
*Main> palindrome "a great good haskell"
False
*Main> 

You can find my Haskell notebook (and my daily progress) here. (thanks to Dropbox)