带有类型错误的HUnit TestCase

时间:2011-03-23 19:59:52

标签: haskell hunit

我写了一个类似于LISP的flatten

的函数
data NestedList a = Elem a | List [NestedList a]

flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List xs) = concatMap flatten xs

这两个测试用例运行良好:

test1 = TestCase (assertEqual "test singleton" [5] (flatten (Elem 5)))
test2 = TestCase (assertEqual "test mixed" 
                              [1,2,3,4]
                              (flatten (List [Elem 1, 
                                              List [Elem 2, Elem 3],
                                              Elem 4])))

但是这个报告了一个类型错误:

test3 = TestCase (assertEqual "test empty" [] (flatten (List [])))

从REPL进行测试工作正常:

*Main> [] == flatten (List [])
True

为什么我收到错误,我应该如何为空列表编写测试用例?

编辑:以下是确切的错误消息:

Ambiguous type variable `a0' in the constraints:
  (Show a0) arising from a use of `assertEqual'
            at D:\haskell\source.hs:61:19-29
  (Eq a0) arising from a use of `assertEqual'
          at D:\haskell\source.hs:61:19-29
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `TestCase', namely
  `(assertEqual "test empty" [] (flatten (List [])))'

2 个答案:

答案 0 :(得分:7)

我猜测问题是编译器无法弄清楚空列表的类型。它可能是[Int][Char],真的。尝试给它一些类型,这种类型无关紧要。

test3 = TestCase (assertEqual "test empty" ([] :: [Int]) (flatten (List [])))

请注意,在其他情况下,编译器可以推断出列表的类型。

答案 1 :(得分:2)

正如错误消息已经告诉您的那样,您必须在单元测试中将类型签名添加到列表中。可能是这样的:

test3 = TestCase (assertEqual "test empty" ([]::[()]) (flatten (List [])))