具有高阶函数的Haskell中List的回文

时间:2018-01-07 22:21:35

标签: haskell

这是我检查列表是否为回文的代码:

isPalindrome :: Eq a => [a] -> Bool

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

是否可以通过在Haskell中使用高阶函数来实现?

1 个答案:

答案 0 :(得分:2)

您可以尝试foldr + zipWith组合:

isPalindrome xs = foldr (&&) True $ zipWith (==) xs (reverse xs)
  • zipWith (==) xs (reverse xs)会生成一个[Bool]列表:如果是回文,它只会包含True个值
  • foldr (&&) True将使用zipWith函数的结果来测试所有值是否为True

它也可以简化为:

isPalindrome xs = and $ zipWith (==) xs (reverse xs)

在GHCi中:

Prelude> isPalindrome [1,2,1]
True
Prelude> isPalindrome [1,2,1,1]
False
Prelude> isPalindrome "salas"
True
Prelude> isPalindrome "salsa"
False