3

我编写了下面的代码来测试列表是否是回文。令我惊讶的是,它没有编译错误“使用 == .... 导致 (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)我如何告诉编译器leftHalfrightHalf是列表?
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
4

3 回答 3

4

为了测试两个列表是否相等,必须可以测试列表中的项目是否相等。因此,您的类型列表[a]必须确保它aEq.

另外,作为风格问题:

x = if c then True else False

可以替换为

x = c
于 2012-05-03T14:52:47.210 回答
2

查看Eq类型类:

ghci> :i (==)
class Eq a where
  (==) :: a -> a -> Bool
  ...
    -- Defined in GHC.Classes
infix 4 ==

您需要的isPalindrome.

另外,这段代码

if (leftHalf == reverse rightHalf)
              then True
              else False

不必要的长。

于 2012-05-03T14:54:00.383 回答
1

您应该将类​​型更改为:

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

找到中心真的是无关紧要的,只需编写就足够了xs == reverse xs- 当您计算时,length xs您会遍历所有列表并且没有经济性。

于 2012-05-03T18:53:28.060 回答