我编写了下面的代码来测试列表是否是回文。令我惊讶的是,它没有编译错误“使用 == .... 导致 (Eq a) 没有实例”。我的假设是编译器不知道这一点leftHalf
并且rightHalf
是列表。
isPalindrome :: [a] -> Bool
isPalindrome [] = False
isPalindrome xs = if (leftHalf == reverse rightHalf)
then True
else False
where leftHalf = take center xs
rightHalf = drop center xs
center = if even (length xs)
then (length xs) `div` 2
else ((length xs) - 1) `div` 2
1)我如何告诉编译器leftHalf
和rightHalf
是列表?
2) 我将如何使用模式匹配或其他 haskell 语言功能来解决这个问题?
编辑:谢谢大家的意见。特别提到 Matt Fenwick 的文档链接和 Duri 的优雅提示。我将在下面写下最终解决方案以防万一
isPalindrome' :: (Eq a) => [a] -> Bool
isPalindrome' [] = False
isPalindrome' xs = if p then True else False
where p = leftHalf == rightHalf
leftHalf = take c xs
rightHalf = take c (reverse xs)
c = div l 2
l = length xs
isPalindrome'
可以像黛米指出的那样改进
isPalindrome'' :: (Eq a) => [a] -> Bool
isPalindrome'' [] = False
isPalindrome'' xs = if (reverse xs) == xs then True else False