如何证明单子是函子和应用函子? [英] How to show that a monad is a functor and an applicative functor?

查看:133
本文介绍了如何证明单子是函子和应用函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从理论上讲,单子元是函子的一个子集,特别是应用函子,即使在Haskell的类型系统中未标明它也是如此.

Monads are known to be theoretically a subset of functors and specifically applicative functors, even though it's not indicated in Haskell's type system.

知道给定单子并以returnbind为基础,怎么做:

Knowing that, given a monad and basing on return and bind, how to:

  • 派生fmap
  • 派生<*>吗?
  • derive fmap,
  • derive <*> ?

推荐答案

好吧,fmap只是(a -> b) -> f a -> f b,也就是说,我们要用纯函数转换单子动作的结果.用do标记很容易写:

Well, fmap is just (a -> b) -> f a -> f b, i.e. we want to transform the monadic action's result with a pure function. That's easy to write with do notation:

fmap f m = do
  a <- m
  return (f a)

或者写为原始":

fmap f m = m >>= \a -> return (f a)

可通过 Control.Monad.liftM .

pure :: a -> f a当然是return. (<*>) :: f (a -> b) -> f a -> f b有点棘手.我们有一个动作返回一个函数,一个动作返回其参数,并且我们想要一个动作返回其结果.再次使用符号:

pure :: a -> f a is of course return. (<*>) :: f (a -> b) -> f a -> f b is a little trickier. We have an action returning a function, and an action returning its argument, and we want an action returning its result. In do notation again:

mf <*> mx = do
  f <- mf
  x <- mx
  return (f x)

或者,已废止:

mf <*> mx =
  mf >>= \f ->
  mx >>= \x ->
  return (f x)

多田!它可以作为 ,因此我们可以为任何单子M给出FunctorApplicative的完整实例,如下所示:

Tada! This is available as Control.Monad.ap, so we can give a complete instance of Functor and Applicative for any monad M as follows:

instance Functor M where
  fmap = liftM

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

理想情况下,我们可以直接在Monad中指定这些实现,以减轻为每个monad定义单独实例的负担,例如使用

Ideally, we'd be able to specify these implementations directly in Monad, to relieve the burden of defining separate instances for every monad, such as with this proposal. If that happens, there'll be no real obstacle to making Applicative a superclass of Monad, as it'll ensure it doesn't break any existing code. On the other hand, this means that the boilerplate involved in defining Functor and Applicative instances for a given Monad is minimal, so it's easy to be a "good citizen" (and such instances should be defined for any monad).

这篇关于如何证明单子是函子和应用函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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