【发布时间】:2016-01-16 12:16:01
【问题描述】:
假设我有一个函数:
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead xs = Just $ head xs
还有一个测试:
describe "Example.safeHead" $ do
it "returns the head" $ do
safeHead [1,2,3] `shouldBe` Just 1
it "returns Nothing for an empty list" $
safeHead [] `shouldBe` Nothing
然而这会产生:
No instance for (Eq a0) arising from a use of ‘shouldBe’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
instance (Eq a, Eq b) => Eq (Either a b)
-- Defined in ‘Data.Either’
instance forall (k :: BOX) (s :: k). Eq (Data.Proxy.Proxy s)
-- Defined in ‘Data.Proxy’
instance (GHC.Arr.Ix i, Eq e) => Eq (GHC.Arr.Array i e)
-- Defined in ‘GHC.Arr’
...plus 88 others
In the second argument of ‘($)’, namely
‘safeHead [] `shouldBe` Nothing’
In a stmt of a 'do' block:
it "returns Nothing for an empty list"
$ safeHead [] `shouldBe` Nothing
In the second argument of ‘($)’, namely
‘do { it "returns the head"
$ do { safeHead [...] `shouldBe` Just 1 };
it "returns Nothing for an empty list"
$ safeHead [] `shouldBe` Nothing }’
为什么?我该如何解决?
【问题讨论】:
-
safeHead [] `shouldBe` Nothing的类型不明确,因为没有什么可以告诉编译器在比较列表元素时使用哪种元素类型(当然,没关系,因为没有元素,但编译器不知道)。您可以通过提供显式类型来修复它:safeHead [] `shouldBe` (Nothing :: Maybe Int)。
标签: haskell testing monads assertions hspec