简体   繁体   中英

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

In Haskell, class Monad is declared as:

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?

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 >>= ?

How can I show that Monad is actually Functor , which is declared like this?

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

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

These are all in the documentation.

Specifically, how can I write pure and <*> in terms of return and >>= ?

See http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#t:Monad , specifically this section:

Furthermore, the Monad and Applicative operations should relate as follows:

 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 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:

As a consequence of these laws, the Functor instance for f will satisfy

fmap fx = pure f <*> x

Which of course, using what I quoted above, you can use to implement fmap in terms of return and >>= .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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