Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple flatMap methods for a single monad?

Does it make sense to define multiple flatMap (or >>= / bind in Haskell) methods in a Monad? The very few monads I actually use (Option, Try, Either projections) only define one flatMap method.

For exemple, could it make sense to define a flatMap method on Option which would take a function producing a Try? So that Option[Try[User]] would be flattened as Option[User] for exemple? (Considering loosing the exception is not a problem ...)

Or a monad should just define one flatMap method, taking a function which produces the same kind of monad? I guess in this case the Either projections wouldn't be monads? Are they?

like image 912
Sebastien Lorber Avatar asked May 06 '13 21:05

Sebastien Lorber


1 Answers

I have once seriously thought about this. As it turns out, such a construct (aside from losing all monadic capabilities) is not really interesting, since it is sufficient to provide a conversion from the inner to the outer container:

joinWith :: (Functor m, Monad m) => (n a -> m a) -> m (n a) -> m a
joinWith i = join . (fmap i)

bindWith :: (Functor m, Monad m) => (n a -> m a) -> m a -> (a -> n a) -> m a
bindWith i x f = joinWith i $ fmap f x

*Main>  let maybeToList = (\x -> case x of Nothing -> []; (Just y) -> [y])
*Main>  bindWith maybeToList [1..9] (\x -> if even x then Just x else Nothing)
[2,4,6,8]
like image 85
phipsgabler Avatar answered Oct 10 '22 01:10

phipsgabler