本文介绍了应用函子和monad之间的等价性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 人们说单子是应用函数的延伸,但我没有看到。我们来看一个应用函子的例子: 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 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 因此,单子是应用函子的延伸任何单子都可以变成一个适用的函子。实际上,标准库中的类(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 = liftMinstance Applicative T where pure = return (<*>) = apliftM is defined asliftM :: (Monad m) => (a1 -> r) -> m a1 -> m rliftM f m1 = do { x1 <- m1; return (f x1) }ap is defined asap :: (Monad m) => m (a -> b) -> m a -> m bap = liftM2 idliftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m rliftM2 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之间的等价性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 01:29