Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is `join` implemented in Maybe/List monad? [duplicate]

Tags:

haskell

monads

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.

like image 211
Tim Avatar asked Sep 11 '25 20:09

Tim


2 Answers

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.

like image 100
Bartek Banachewicz Avatar answered Sep 14 '25 09:09

Bartek Banachewicz


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
like image 45
chepner Avatar answered Sep 14 '25 11:09

chepner