# 99 questions/Solutions/6

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(Just wanted to post a solution using a fold.) |
|||

Line 10: | Line 10: | ||

isPalindrome' [_] = True |
isPalindrome' [_] = True |
||

isPalindrome' xs = (head xs) == (last xs) && (isPalindrome' $ init $ tail xs) |
isPalindrome' xs = (head xs) == (last xs) && (isPalindrome' $ init $ tail xs) |
||

+ | </haskell> |
||

+ | |||

+ | 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. |
||

+ | |||

+ | <haskell> |
||

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

+ | isPalindrome'' xs = foldl (\acc (a,b) -> if a == b then acc else False) True input --just to be different |
||

+ | where |
||

+ | input = zip xs (reverse xs) |
||

</haskell> |
</haskell> |

## Revision as of 04:52, 28 February 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 --just to be different where input = zip xs (reverse xs)