简体   繁体   English

我怎样才能证明`Monad` 实际上是`Applicative` 和`Functor`?

[英]How can I show that `Monad` is actually `Applicative` and `Functor`?

In Haskell, class Monad is declared as:在 Haskell 中,类Monad被声明为:

class   Applicative m   =>  Monad   m   where
return  ::  a   ->  m   a
(>>=)   ::  m   a   ->  (a  ->  m   b)  ->  m   b
return  =   pure

How can I show that Monad is actually Applicative , which is declared like this?我怎样才能证明Monad实际上是Applicative ,它是这样声明的?

class   Functor f   =>  Applicative f   where
pure    ::  a   ->  f   a
(<*>)   ::  f   (a  ->  b)  ->  f   a   ->  f   b

Specifically, how can I write pure and <*> in terms of return and >>= ?具体来说,我如何在return>>=方面编写pure<*>

How can I show that Monad is actually Functor , which is declared like this?我怎样才能证明Monad实际上是Functor ,它是这样声明的?

class   Functor f   where
fmap    ::  (a  ->  b)  ->  f   a   ->  f   b

Specifically, how can I write fmap in terms of return and >>= ?具体来说,如何根据return>>=编写fmap

These are all in the documentation.这些都在文档中。

Specifically, how can I write pure and <*> in terms of return and >>= ?具体来说,我如何在 return 和>>=方面编写pure<*>

See http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#t:Monad , specifically this section:请参阅http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#t:Monad ,特别是本节:

Furthermore, the Monad and Applicative operations should relate as follows:此外,Monad 和 Applicative 操作应如下相关:

 pure = return (<*>) = ap

and note that ap was a standard Monad function long before Applicative was introduced as a standard part of the language, and is defined as ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) }并注意ap早在 Applicative 作为语言的标准部分被引入之前就是一个标准的 Monad 函数,并且被定义ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) } ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) }

Specifically, how can I write fmap in terms of return and >>=?

The Control.Applicative documentation says: Control.Applicative 文档说:

As a consequence of these laws, the Functor instance for f will satisfy作为这些定律的结果, fFunctor实例将满足

fmap fx = pure f <*> x

Which of course, using what I quoted above, you can use to implement fmap in terms of return and >>= .当然,使用我上面引用的内容,您可以使用return>>=来实现fmap

And as @duplode points out, there are also liftM for Monads, and liftA for Applicatives, which are (essentially, although they're not defined literally that way) synonyms of fmap , specialised to their particular type classes.正如@duplode 指出的那样,还有用于 Monads 的liftM和用于 Applicatives 的LiftA ,它们是(本质上,虽然它们的字面定义不是那样) fmap同义词,专门用于它们的特定类型类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM