我编写了下面的代码来测试列表是否是回文。令我惊讶的是,它没有编译错误“No instance for (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'
可以像 Demi 指出的那样改进 isPalindrome'' :: (Eq a) => [a] -> Bool
isPalindrome'' [] = False
isPalindrome'' xs = if (reverse xs) == xs then True else False
最佳答案
查看 Eq
类型类:
ghci> :i (==)
class Eq a where
(==) :: a -> a -> Bool
...
-- Defined in GHC.Classes
infix 4 ==
你需要的是 a type constraint 上的
isPalindrome
。另外,这段代码
if (leftHalf == reverse rightHalf)
then True
else False
不必要地长。
关于haskell - 作业 : Comparing intermediate expressions with == in Haskell,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10433768/