Cannot find function similar to liftM2

江枫思渺然 提交于 2019-12-18 08:24:55

问题


myLiftM2 ::  Monad m => (a -> a1 -> m b) -> m a -> m a1 -> m b
myLiftM2 f x y = x >>= (\r1 -> y >>= (\r2 -> f r1 r2))

In liftM2 f return b, but myLiftM2 return m b


回答1:


tl;dr: Use join :: Monad m => m (m a) -> m a since a plain lift will return m (m a). E.g. write

join $ liftM2 f a b

But also...

liftMs can also be written with Applicative -- e.g.

liftM2 a b c   == a <$> b <*> c
liftM3 a b c d == a <$> b <*> c <*> d

etc.

In this case, if you're willing to write in that style, you can write it cleanly and easily:

import Control.Applicative

myLiftM2 :: (Monad m, Applicative m) => (a -> a1 -> m b) -> m a -> m a1 -> m b
myLiftM2 f x y = join $ f <$> x <*> y

Edit:
As Daniel Wagner points out, you can just as easily write

join $ liftM2 a b c

as the equivalent

join $ a <$> b <*> c

My recommendation of the applicative style is for readability and is a separate point.



来源:https://stackoverflow.com/questions/20163880/cannot-find-function-similar-to-liftm2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!