gpt4 book ai didi

Haskell - 你能有一个不是应用仿函数的单子(monad)吗?

转载 作者:行者123 更新时间:2023-12-03 15:08:03 24 4
gpt4 key购买 nike

this set of slides by Jim Duey at slide 13 - 他建议所有的 Monad 都是应用仿函数。

enter image description here

在 Haskell 7.7 编译器输出中 - 我看到以下内容(另一个示例 is here ):

‛Parser’ is an instance of Monad but not Applicative - this will become an error in GHC 7.10, under the Applicative-Monad Proposal.



这是否意味着 Haskell 编译器当前可以容忍不是应用仿函数的 Monad - 但计划是纠正这个问题?

最佳答案

现在Applicative不是 Monad 的父类(super class)

instance Monad m where ...      -- this is how it is today, instead of
instance Applicative m => Monad m where ...

但计划在 GHC 7.10 中更改为 ApplicativeMonad 的父类(super class).为了帮助过渡,在 GHC 7.7 和 7.8 中,每当 GHC 遇到 Monad 时都会发出警告。没有 Applicative实例。

现在有点令人困惑的是所有有效的 Monad s 是应用仿函数,即使它们不是 instanceApplicative .我们可以写
fmapM :: Monad m => (a -> b) -> m a -> m b
fmapM f ma = ma >>= return . f -- a.k.a. `liftM`

pureM :: Monad m => a -> m a
pureM = return

ap :: Monad m => m (a -> b) -> m a -> m b
ap mf ma = do { f <- mf; a <- ma; return (f a) } -- a.k.a. `ap`

它们共同满足 Functor 的签名和法律和 Applicative .这就是为什么添加父类(super class)约束是有意义的,而且在第一种情况下它不存在纯属历史意外— Applicative s 是在 Monad 之后很久才被发现和普及的是。
newtype WrappedMonad m a = WM (m a)

instance Monad m => Functor (WrappedMonad m) where
fmap f (WM m) = WM (liftM f m)

instance Monad m => Applicative (WrappedMonad m) where
pure = WM . return
WM mf <*> WM ma = WM $ mf `ap` ma

更多信息 ApplicativeMonad相关,看看我之前在这里写的一个答案: Is it better to define Functor in terms of Applicative in terms of Monad, or vice versa?

关于Haskell - 你能有一个不是应用仿函数的单子(monad)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20027072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com