开发者

HUnit TestCase with a Type Error

I've written a function similar to LISP's 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:

*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\sou开发者_StackOverflow中文版rce.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. 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 [])))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜