[英]How can I show that `Monad` is actually `Applicative` and `Functor`?
在 Haskell 中,類Monad
被聲明為:
class Applicative m => Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
return = pure
我怎樣才能證明Monad
實際上是Applicative
,它是這樣聲明的?
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
具體來說,我如何在return
和>>=
方面編寫pure
和<*>
?
我怎樣才能證明Monad
實際上是Functor
,它是這樣聲明的?
class Functor f where
fmap :: (a -> b) -> f a -> f b
具體來說,如何根據return
和>>=
編寫fmap
?
這些都在文檔中。
具體來說,我如何在 return 和
>>=
方面編寫pure
和<*>
?
請參閱http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#t:Monad ,特別是本節:
此外,Monad 和 Applicative 操作應如下相關:
pure = return (<*>) = ap
並注意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 >>=?
作為這些定律的結果,
f
的Functor
實例將滿足fmap fx = pure f <*> x
當然,使用我上面引用的內容,您可以使用return
和>>=
來實現fmap
。
正如@duplode 指出的那樣,還有用於 Monads 的liftM和用於 Applicatives 的LiftA ,它們是(本質上,雖然它們的字面定義不是那樣) fmap
同義詞,專門用於它們的特定類型類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.