我编写了一个类似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 [])))'发布于 2011-03-23 20:20:24
我猜问题是编译器找不出空列表的类型。可能是[Int],[Char],任何真正的东西。试着给它一些类型,哪种类型完全不重要。
test3 = TestCase (assertEqual "test empty" ([] :: [Int]) (flatten (List [])))
注在其他情况下,编译器可以推断列表的类型。
发布于 2011-03-23 20:20:40
正如错误消息已经告诉您的,您必须将类型签名添加到单元测试中的列表中。可能是这样的:
test3 = TestCase (assertEqual "test empty" ([]::[()]) (flatten (List [])))https://stackoverflow.com/questions/5410919
复制相似问题