找不到类似liftM2的功能 [英] Cannot find function similar to liftM2

查看:209
本文介绍了找不到类似liftM2的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在liftM2中返回b,但myLiftM2返回mb

解决方案

tl; dr:使用 join:Monad m => m(m a) - > m a ,因为普通电梯将返回 m(m a)。例如。写

 加入$ liftM2 fab 

但是...



liftM s也可以写成 Applicative - 例如

  liftM2 abc ==一个< $> b * c 
liftM3 a b c d == a< $> b * c * d

等。



在这种情况下,如果你愿意以这种风格写作,你可以干净而轻松地写出它:

  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

编辑:

Daniel Wagner指出你可以很容易地写出

  join $ liftM2 abc 

作为等价物

 加入$ a< $> b * c 

我对应用风格的建议是为了可读性,并且是一个单独的点。


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

解决方案

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.

这篇关于找不到类似liftM2的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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