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

标签 haskell ghc

我正在阅读一篇关于 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/

相关文章:

haskell - GHC 中自动特化的传递性

haskell - 在 ghc-7.6.1 之后的世界中,DynamicException 等价物是什么?

haskell - 创建 GHC.Prim.Any,而不是自由变量 [在多态函数中]

haskell - 为什么 haskell 版本控制策略有两个主要版本的地方,而不是语义版本控制中的一个?

haskell - Haskell 中的函数缩减是如何工作的?

haskell - 从字符串中消除连续重复

haskell - Haskell 中函数 makeSum 的求值顺序

haskell - UndecidableInstances 何时安全?关于 GHC 扩展的一些一般性问题

memory - 如何限制 Haskell 线程的内存使用量

Haskell 将整数转换为 Int?