Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "return Nothing" return Nothing?

"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
like image 939
Jeffrey Benjamin Brown Avatar asked Aug 08 '17 03:08

Jeffrey Benjamin Brown


1 Answers

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
like image 200
Rein Henrichs Avatar answered Nov 16 '22 00:11

Rein Henrichs