dbyrne
dbyrne

Reputation: 61011

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

Upvotes: 3

Views: 695

Answers (2)

fuz
fuz

Reputation: 92966

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

Upvotes: 2

Joel Burget
Joel Burget

Reputation: 1438

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.

Upvotes: 7

Related Questions