HSpec Nothing expectation failing to compile

落爺英雄遲暮 提交于 2019-12-01 00:53:07

So, it's something about Nothing itself, that it cannot be compared by equals?

What's Nothing's type? It's Nothing :: Maybe a. And GHC doesn't like a in this context: "The type variable ‘a0’ is ambiguous". After all, shouldBe takes anything that can be compared with (==) and shown. And Maybe a is an instance of Eq if a is an instance of Eq. GHC can't possibly know which a you want to use, so you need to specify it by hand:

  describe "safeHead" $
    it "should return Nothing for empty list" $
      safeHead [] `shouldBe` (Nothing :: Maybe Int)

That's not coercion, you're just making clear which of all possible types you want to use. Other examples:

  describe "safeHead" $
    it "should return Nothing for empty list" $ do
      safeHead [] `shouldBe` (Nothing :: Maybe Int)
      safeHead [] `shouldBe` (Nothing :: Maybe ())
      safeHead [] `shouldBe` (Nothing :: Maybe Integer)
      safeHead [] `shouldBe` (Nothing :: Maybe Char)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!