Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

haskell - Cannot find function similar to liftM2

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

In liftM2 f return b, but myLiftM2 return m b

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...