似乎我理解错了,但我尝试了以下操作:
GHCi, version 8.6.5
Nothing == Nothing
=> True
Nothing == (pure Nothing)
=> False
pure Nothing
=> Nothing
Run Code Online (Sandbox Code Playgroud)
你能解释一下这里发生了什么吗?
Atn*_*nNn 13
pure Nothing
代码中的两个使用不同的pure
.
如果您检查的类型pure Nothing
,您可以看到选择的版本pure
取决于类型f
。
GHCi> :t pure Nothing
pure Nothing :: Applicative f => f (Maybe a)
Run Code Online (Sandbox Code Playgroud)
当您进入pure Nothing
交互模式时,f
推断为IO
并IO
打印操作结果。这是 GHCi 提供的快捷方式,在常规 Haskell 代码中不会发生。
GHCi> pure Nothing
Nothing
GHCi> pure Nothing :: IO (Maybe ())
Nothing
Run Code Online (Sandbox Code Playgroud)
但是,当与 比较pure Nothing
时Nothing
,f
推断为Maybe
。这将创建两层Maybe
,使类型Maybe (Maybe a)
GHCi> Nothing == pure Nothing
False
GHCi> Just Nothing == pure Nothing
True
GHCi> pure Nothing :: Maybe (Maybe ())
Just Nothing
Run Code Online (Sandbox Code Playgroud)