blazing
blazing

Reputation: 577

Palindrome of List in Haskell with Higher-Order functions

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

Answers (1)

Szymon Stepniak
Szymon Stepniak

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 values
  • foldr (&&) 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

Related Questions