# 99 questions/Solutions/6

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(simple example of reader monad) |
m |
||

Line 36: | Line 36: | ||

p rev (x:xs) [_] = rev == xs |
p rev (x:xs) [_] = rev == xs |
||

p rev xs [] = rev == xs |
p rev xs [] = rev == xs |
||

+ | </haskell> |
||

+ | |||

+ | Here's one using foldr and zipWith. |
||

+ | |||

+ | <haskell> |
||

+ | palindrome :: (Eq a) => [a] -> Bool |
||

+ | palidrome xs = foldr (&&) True $ zipWith (==) xs (reverse xs) |
||

</haskell> |
</haskell> |

## Revision as of 05:53, 25 October 2011

(*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).

isPalindrome :: (Eq a) => [a] -> Bool isPalindrome xs = xs == (reverse xs)

isPalindrome' [] = True isPalindrome' [_] = True isPalindrome' xs = (head xs) == (last xs) && (isPalindrome' $ init $ tail xs)

Here's one to show it done in a fold just for the fun of it. Do note that it is less efficient then the previous 2 though.

isPalindrome'' :: (Eq a) => [a] -> Bool isPalindrome'' xs = foldl (\acc (a,b) -> if a == b then acc else False) True input where input = zip xs (reverse xs)

Another one just for fun:

isPalindrome''' :: (Eq a) => [a] -> Bool isPalindrome''' = Control.Monad.liftM2 (==) id reverse

Here's one that does half as many compares:

palindrome :: (Eq a) => [a] -> Bool palindrome xs = p [] xs xs where p rev (x:xs) (_:_:ys) = p (x:rev) xs ys p rev (x:xs) [_] = rev == xs p rev xs [] = rev == xs

Here's one using foldr and zipWith.

palindrome :: (Eq a) => [a] -> Bool palidrome xs = foldr (&&) True $ zipWith (==) xs (reverse xs)