說我有一個功能:測試函數返回一個單子可能
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)'。 – user2407038