这是我检查列表是否为回文的代码:
isPalindrome :: Eq a => [a] -> Bool
isPalindrome [] = True
isPalindrome [_] = True
isPalindrome xs = (head xs == last xs) && (isPalindrome (tail (init xs)))
是否可以通过在Haskell中使用高阶函数来实现?
答案 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