应用函子和monad之间的等价性 [英] the equivalence between applicative functor and monad

查看:130
本文介绍了应用函子和monad之间的等价性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们说单子是应用函数的延伸,但我没有看到。我们来看一个应用函子的例子:(*):f(a-> b) - > f a - > f b

  [(+ 3)] * [2,3,4] 

现在,我也希望我可以做与monad相同的事情,这意味着我可以应用2个参数:一个上下文包含一个函数,另一个上下文获取上下文。但对于monad,我不行。我所需要的就是编写一个丑陋的函数,像这样:

  [2,3,4]>> =(\\ \\ x-> [x + 3])

当然,您可以说 [(+ 3)] 相当于 [\ x->(x + 3)] 。但至少,这个功能是在上下文中。

最后,我在这里看不到等值或扩展。 Monad是另一种风格,在另一个故事中很有用。



对不起我的无知。 如果<$ c $

解决方案 c> T 是 Monad 的一个实例,那么您可以使它成为 Applicative

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $实例函数T其中
fmap = liftM

实例应用T其中
pure =返回
(*)= ap

liftM 被定义为

  liftM ::(Monad m)=> ; (a1→r)→> m a1  - > m r 
liftM f m1 = do {x1 < - m1;返回(f x1)}

ap 是定义为

  ap ::(Monad m)=> m(a  - > b) - > m a  - > m b 
ap = liftM2 id

liftM2 ::(Monad m)=> (a1→a2→r)→> m a1 - > m a2 - > m r
liftM2 f m1 m2 = do {x1 < - m1; x2 <-m2;返回(f x1 x2)}

因此,单子是应用函子的延伸任何单子都可以变成一个适用的函子。实际上,标准库中的类(code> Monad )不是从类 Applicative 。


People say monads are an extension of applicative functors, but I don't see that. Let's take an example of applicative functor: (<*>) :: f(a->b) -> f a -> f b

[(+3)] <*> [2,3,4]

Now, I also expect I can do the same thing as monad, it means I can apply 2 parameters: a context contains a function, and another context to get a context. But for monad, I can't. All I need is to write an ugly function like this:

[2,3,4] >>= (\x->[x+3])

Yes, of course, you can say that [(+3)] is equivalent to [\x->(x+3)]. But at least, this function is in context.

Finally, I don't see the equivalence or extension here. Monad is a different style and useful in another story.

Sorry for my ignorance.

解决方案

If T is an instance of Monad, then you can make it an instance of Applicative like this:

instance Functor T where
    fmap = liftM

instance Applicative T where
    pure = return
    (<*>) = ap

liftM is defined as

liftM   :: (Monad m) => (a1 -> r) -> m a1 -> m r
liftM f m1              = do { x1 <- m1; return (f x1) }

ap is defined as

ap                :: (Monad m) => m (a -> b) -> m a -> m b
ap                =  liftM2 id

liftM2  :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2          = do { x1 <- m1; x2 <- m2; return (f x1 x2) }

So, "monads are an extension of applicative functors" in the sense that any monad can be made into an applicative functor. Indeed, it is widely (not universally) considered a bug in the standard library that class Monad does not derive from class Applicative.

这篇关于应用函子和monad之间的等价性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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