简体   繁体   English

带有类型错误的HUnit TestCase

[英]HUnit TestCase with a Type Error

I've written a function similar to LISP's flatten : 我写了一个类似于LISP flatten的函数:

data NestedList a = Elem a | List [NestedList a]

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

These two test-cases work fine: 这两个测试用例工作正常:

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])))

However this one reports a type error: 但是这个报告了一个类型错误:

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

Testing from the REPL works fine: REPL的测试工作正常:

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

Why am I getting an error, and how should I write a test-case for an empty list? 为什么我会收到错误,如何为空列表编写测试用例?

EDIT: Here is the exact error message: 编辑:这是确切的错误消息:

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 [])))'

I'm guessing the problem is the compiler can't figure out the type of the empty list. 我猜测问题是编译器无法弄清楚空列表的类型。 It could be [Int] , [Char] , anything really. 它可能是[Int][Char] ,真的。 Try giving it some type, which type exactly doesn't matter. 尝试给它一些类型,哪种类型无关紧要。

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

Note in the other cases the compiler can deduce the type of list. 请注意,在其他情况下,编译器可以推断出列表的类型。

As the error message already tells you, you have to add a type signature to the list in the units test. 正如错误消息已经告诉您的那样,您必须在单元测试中将类型签名添加到列表中。 Possibly like this: 可能是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM