Haskell中的*>和>>有什么区别?

从文档:

(>>) : 依次组合两个动作,丢弃第一个动作产生的任何值

(*>):序列操作,丢弃第一个参数的值。

在我看来,两者都在做同样的工作。

回答

在实践中,它们是等效的。

从历史上看,Haskell 没有Applicative类型类(因此没有*>),而只有一个Monad类型类(带有>>)。

在某一时刻,Applicative被做成了Monad. 那时,它被引入*>为 的一个稍微更通用的变体>>,它不需要与 monad 一起工作,而只需要与应用函子一起工作。

(*>) :: Applicative f => f a -> f b -> f b
(>>) :: Monad f       => f a -> f b -> f b

最终结果是,当使用 applicatives 时,我们只能使用*>,而在使用 monads(也是 applicatives)时,我们可以使用*>>>互换使用,因为在这种情况下它们必须是等效的。

其他几个与 monad 相关的函数也被类似地推广到 applicatives:

  • return 概括为 pure
  • ap 概括为 <*>
  • mapM 概括为 traverse
  • One small correction: the `*>` operator was part of `Applicative` before it became a superclass of `Monad` (see [base-4.7.0.0](https://hackage.haskell.org/package/base-4.7.0.0/docs/Control-Applicative.html)). So, the history is: (1) Haskell has `Monad` only with `>>`; (2) `Applicative` gets introduced with corresponding `*>` operator; (3) `Applicative` becomes superclass of `Monad`, after which they're equivalent in practice.

以上是Haskell中的*&gt;和&gt;&gt;有什么区别?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>