haskellmonads

Trouble understanding Haskell function


I'm having trouble understanding why the following code correctly compiles:

f :: a -> Maybe a
f = return Just 3

return Just has a type of Monad m => m (a -> Maybe a) so I'm not sure why passing in an Int unwraps the monad.

You can even get a little crazy with it:

f :: a -> Maybe a
f = return Just (Just . Just . Just . Just)

Can someone explain what exactly is going on here?


Solution

  • You're using return from the reader monad (->) Int, which is defined as const. In this case return Just has type Int -> a -> Maybe a.

    f = return Just 3
      = const Just 3
      = Just