Saturday 4 June 2016

Haskell : Check whether given string (or) list is a palindrome or not


checkPalindrome.hs

isPalindrome :: String -> Bool
isPalindrome [] = True
isPalindrome xs = (xs == (reverse xs))


*Main> :load checkPalindrome.hs
[1 of 1] Compiling Main             ( checkPalindrome.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isPalindrome ""
True
*Main> 
*Main> isPalindrome "abcd"
False
*Main> 
*Main> isPalindrome "madam"
True
*Main>


Since String is internally implemented as list of characters, same logic is used on list of characters also.

*Main> isPalindrome []
True
*Main> 
*Main> isPalindrome ['a', 'b', 'c', 'd']
False
*Main> 
*Main> isPalindrome ['m', 'a', 'd', 'a', 'm']
True

We can rewrite the above logic using head and last functions like below.


checkPalindrome.hs
isPalindrome :: String -> Bool
isPalindrome [] = True
isPalindrome xs = ((head xs) == (last xs)) && (isPalindrome (take ((length xs)-2) (tail xs)))

*Main> :load checkPalindrome.hs
[1 of 1] Compiling Main             ( checkPalindrome.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isPalindrome  ""
True
*Main> 
*Main> isPalindrome  "a"
True
*Main> 
*Main> isPalindrome "aa"
True
*Main> 
*Main> isPalindrome "abc" 
False
*Main> 
*Main> isPalindrome "aba"
True
*Main> 
*Main> isPalindrome  "madam"
True
*Main> 
*Main> isPalindrome  "aasdsa"
False
*Main> 




Previous                                                 Next                                                 Home

No comments:

Post a Comment