gpt4 book ai didi

haskell - 为什么 (>>) 没有定义为 (*>)?

转载 作者:行者123 更新时间:2023-12-03 11:51:07 25 4
gpt4 key购买 nike

GHC 目前实现 >>作为

(>>) :: m a -> m b -> m b
m >> k = m >>= \_ -> k

为什么不改为执行以下操作?
(>>) :: m a -> m b -> m b
m >> k = m *> k

现在,我在想 >>=做某事 *>没有。

但是一切都在语法上有效(如在类型方面),所以很难解释为什么它不起作用。
也许 monad 实例做了一些 applicative 实例没有做的计算,但我认为这会破坏类型的语义。

更新 我只能选择一个接受的 SO 答案,但 answer by dfeuer非常有见地(特别是对于像我这样对 Haskell 相对缺乏经验的人来说)。

最佳答案

根据 source code 中的评论,这是为了防止人们在重写 *> 时意外创建递归绑定(bind)如>>在他们的Applicative实例。

(>>)        :: forall a b. m a -> m b -> m b
m >> k = m >>= \_ -> k -- See Note [Recursive bindings for Applicative/Monad]

笔记说:

Note: Recursive bindings for Applicative/Monad

The original Applicative/Monad proposal stated that after implementation, the designated implementation of (>>) would become

(>>) :: forall a b. m a -> m b -> m b
(>>) = (*>)

by default. You might be inclined to change this to reflect the stated proposal, but you really shouldn't! Why? Because people tend to define such instances the other way around: in particular, it is perfectly legitimate to define an instance of Applicative (*>) in terms of (>>), which would lead to an infinite loop for the default implementation of Monad! And people do this in the wild.

This turned into a nasty bug that was tricky to track down, and rather than eliminate it everywhere upstream, it's easier to just retain the original default.

关于haskell - 为什么 (>>) 没有定义为 (*>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047395/

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