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>
No comments:
Post a Comment