join
can be defined implemented in terms of >>=
:
join :: Monad m => m (m a) -> m a
join m = m >>= id
Specifically, how is it implemented in a Maybe and a List monad?
Is it in Maybe monad:
join Nothing = Nothing
join (Just (Just x)) = Just x
and in List monad:
join [] = []
join [[xs]] = [xs]
?
Thanks.
join
is implemented exactly once, and it works for all types that are Monads.
The very point of the Monad abstraction is to enable working on different types in the same way. Once you provide >>=
(and return
) for your type, and make sure they follow the Monad laws, any code that is generic enough to only use those operations will work on your type correctly.
join
is just a regular function, implemented in terms of the preexisting (>>=)
function. You don't have to worry about which monad is used; (>>=)
takes care of that.
Conversely, Monad
could have been defined in a way closer to its mathematical definition:
class Monad' m where
return :: a -> m a
join :: m (m a) -> m a
with
(>>=) :: Monad' m => m a -> (a -> m b) -> m b
x >>= f = join (fmap f x)
as the regular function. Then the list-specific definition of join
would just be concat :: [[a]] -> [a]
:
instance Monad' [] where
return x = [x]
join = concat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With