一个monad有多个flatMap方法? [英] Multiple flatMap methods for a single monad?

查看:86
本文介绍了一个monad有多个flatMap方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Monad中定义多个flatMap(在Haskell中为>>=/bind)方法是否有意义? 我实际使用的极少数monad(OptionTryEither投影)仅定义了一个flatMap方法.

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.

例如,在Option上定义一个flatMap方法是否有意义,该方法将使用产生Try的函数?这样,例如,Option[Try[User]]将被扁平化为Option[User]? (考虑释放异常不是问题...)

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 ...)

还是一个monad应该只定义一个flatMap方法,并采用产生相同类型monad的函数?我想在这种情况下,Either投影不会是单子?是吗?

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?

推荐答案

我曾经认真考虑过这一点.事实证明,这样的构造(除了失去所有的monadic功能)并不是真正有趣的,因为它足以提供从内部容器到外部容器的转换:

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]

这篇关于一个monad有多个flatMap方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆