Seb*_*ber 6 monads haskell scala
在Monad中定义多个flatMap(或>>=/ bind在Haskell中)方法是否有意义?极少数单子我实际使用(Option,Try,Either投影)只定义一个flatMap方法.
例如,定义一个flatMap方法Option可以生成一个函数Try吗?那么这样Option[Try[User]]就会被夷为平地Option[User]?(考虑失去异常不是问题......)
或者monad应该只定义一个flatMap方法,采用产生相同类型monad的函数?我想在这种情况下,Either预测不会是monad?是吗?
我曾经认真考虑过这件事.事实证明,这样的构造(除了失去所有monadic功能)并不是很有趣,因为它足以提供从内部到外部容器的转换:
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]
Run Code Online (Sandbox Code Playgroud)