gpt4 book ai didi

haskell - 是否可以仅使用 Applicative 实现 MaybeT?

转载 作者:行者123 更新时间:2023-12-01 08:55:04 27 4
gpt4 key购买 nike

重新访问我的 MaybeT 练习后,我收到警告说我也应该有 Applicative 实例。我试图实现它,但因为我找不到使用 Applicative mm x 应用到 m f 的方法而陷入困境。我需要 Monad m 吗?

newtype MaybeT m x = MaybeT { runMaybeT :: m (Maybe x) }

instance Functor m => Functor (MaybeT m) where
fmap f m = MaybeT $ fmap z $ runMaybeT m where
z (Just x) = Just $ f x
z Nothing = Nothing

instance Applicative m => Applicative (MaybeT m)

最佳答案

我认为你确实需要 Monad .基本上,如果你有

f :: MaybeT m (a -> b)
x :: MaybeT m a

如果,在评估 f <*> x 时,运行展开的 fm返回 Nothing ,然后是 x 的操作根本不应该运行——但如果不使用 m 就无法实现。是 Monad , 自 Applicative组合器直观地总是运行所有子操作。

顺便说一句,生成 Applicative 的最简单方法只是为了满足新的 AMP 要求,就是使用

import Control.Monad (ap)

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

对于 Functor您可以使用 fmap = liftM ,或 DeriveFunctor扩展名。

关于haskell - 是否可以仅使用 Applicative 实现 MaybeT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517053/

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