Reputation: 577
This is my code to check if a list is a palindrome:
isPalindrome :: Eq a => [a] -> Bool
isPalindrome [] = True
isPalindrome [_] = True
isPalindrome xs = (head xs == last xs) && (isPalindrome (tail (init xs)))
Is it possible to do this by using higher-order functions in Haskell?
Upvotes: 3
Views: 2290
Reputation: 42184
You can try foldr
+ zipWith
combination:
isPalindrome xs = foldr (&&) True $ zipWith (==) xs (reverse xs)
zipWith (==) xs (reverse xs)
produces a [Bool]
list: in case of palindrome it will contain only True
valuesfoldr (&&) True
will use the result of zipWith
function to test if all values are True
It can be also simplified to:
isPalindrome xs = and $ zipWith (==) xs (reverse xs)
In GHCi:
Prelude> isPalindrome [1,2,1]
True
Prelude> isPalindrome [1,2,1,1]
False
Prelude> isPalindrome "salas"
True
Prelude> isPalindrome "salsa"
False
Upvotes: 3