Why does “return Nothing” return Nothing?

雨燕双飞 提交于 2019-12-08 15:24:49

问题


"return a" is supposed to wrap a in the context of some Monad:

*Main> :i return
class Applicative m => Monad (m :: * -> *) where
  ...
  return :: a -> m a
  ...
        -- Defined in ‘GHC.Base’

If I ask GHCI what the type of "return Nothing" is, it conforms to that:

*Main> :t return Nothing
return Nothing :: Monad m => m (Maybe a)

But if I evaluate it, I see no outer Monad, just the inner Maybe:

*Main>  return Nothing
Nothing

回答1:


When GHCi goes to print a value, it tries two different things. First, it tries to unify the type with IO a for some a. If it can do that then it executes the IO action and tries to print the result. If it can't do that, it tries to print the given value. In your case, Monad m => m (Maybe a) can be unified with IO (Maybe a).

Reviewing this GHCi session might help:

Prelude> return Nothing
Nothing
Prelude> return Nothing :: IO (Maybe a)
Nothing
Prelude> return Nothing :: Maybe (Maybe a)
Just Nothing
Prelude> Nothing
Nothing


来源:https://stackoverflow.com/questions/45558914/why-does-return-nothing-return-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!