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?
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]
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