gpt4 book ai didi

haskell - GHC 7.10.x 迁移 : why can't one write "pure = return" in the instance Applicative?

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

我正在阅读一篇关于 GHC 7.10.x Migration 的文章.有一些修复错误的建议。

GHC says No instance for (Applicative ...)

If GHC complains that

Foo.hs:7:10: No instance for (Applicative Foo) arising from the superclasses of an instance declaration In the instance declaration for ‘Monad Foo’ then an easy way to fix this error is by defining an Applicative (and possibly a Functor) instance: instance Functor Foo where fmap = liftM -- or alternatively: -- fmap = m >>= pure . f

instance Applicative Foo where
-- NB: DO NOT USE `pure = return`
pure = {- move the definition of `return` from the `Monad` instance here -}

(<*>) = ap {- defined in Control.Monad -}
-- or alternatively:
-- f1 <*> f2 = f1 >>= \v1 -> f2 >>= (pure . v1)

-- NB: DO NOT USE `(*>) = (>>)`
(*>) = {- move the definition of `>>` from the `Monad` instance here -}

instance Monad Foo where
return = pure {- definition moved to `Applicative(pure)` -}

(>>) = (*>) {- definition moved to `Applicative((*>))` -}

{- ...retain other previous definitions... -}


有NB: DO NOT USE `pure = return`DO NOT USE `(*>) = (>>) .为什么一个人不能用?

附言我尝试使用它并已编译。

最佳答案

正如@WillSewell 在评论中暗示的那样,来自 base-4.8.0.0现在return在类型类 Monad有一个默认实现:

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

通过定义 pure = return忘记执行 return手动可以创建一个无限循环的定义,它将通过编译并且只能在运行时检测到。
>>现在是一个不同的故事。它在 >>= 上有一个默认实现中继。只要:
(>>) :: forall a b. m a -> m b -> m b
m >> k = m >>= \_ -> k

*> = >>除非您使用 *>,否则您不会创建无限循环在 >>= 的定义中, 但有 some concern关于 base 中可能的下一个重大变化(这可能会将 >> 的默认实现更改为 >> = *> )所以 *> = >>不鼓励向前兼容。

关于haskell - GHC 7.10.x 迁移 : why can't one write "pure = return" in the instance Applicative?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742643/

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