Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tow definition of function "return" in monad transformer MaybeT

Tags:

haskell

MaybeT is defined as

newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }

And, MaybeT m is also an instance of the Monad class, the function return is defined like

return  = MaybeT . return . Just

But I read that "It would also have been possible (though arguably less readable) to write return = MaybeT . return . return", this confused me.

How does return = MaybeT . return . return equals to return = MaybeT . return . Just ?

like image 433
hl1020 Avatar asked Jan 29 '26 16:01

hl1020


1 Answers

Consider MaybeT's definition:

newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }

First return definition (read it from down to up):

return =
  MaybeT .   -- put `m (Maybe a)` into `MaybeT`: MaybeT (m (Maybe a))
    return . -- put `Maybe a` into external monad: m (Maybe a)
      Just   -- put value into `Maybe`: Maybe a

Maybe is a monad too. It's return is a Just. That's why second MaybeT's return defines exactly the same function:

return =
  MaybeT .   -- put `m (Maybe a)` into `MaybeT`: MaybeT (m (Maybe a))
    return . -- put `Maybe a` into external monad: m (Maybe a)
      return -- it's the same as `Just` for `Maybe`: Maybe a

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!