gpt4 book ai didi

scala - JsResult - Monad 还是 Applicative?

转载 作者:行者123 更新时间:2023-12-04 08:35:15 26 4
gpt4 key购买 nike

我对 Monad 之间的区别之一的理解和 ApplicativeflatMap可在 Monad 上找到,但不是 Applicative .

如果这是真的,我对这些 Scala Play JSON 感到困惑 docs :

So what’s interesting there is that JsResult[A] is a monadic structure and can be used with classic functions of such structures:

flatMap[X](f: A => JsResult[X]): JsResult[X]

etc



但是,然后文档继续说:

Please note that JsResult[A] is not just Monadic but Applicative because it cumulates errors. This cumulative feature makes JsResult[T] makes it not very good to be used with for comprehension because you’ll get only the first error and not all.



因为,据我所知,一个 for-comprehensionflatMap 的语法糖,怎么能 JsResult都是 ApplicativeMonad ?

最佳答案

MonadApplicative 的子类. Applicative apply 操作弱于flatMap .因此apply可以按照 flatMap 实现.

但是 ,在 JsResult (或实际上 Reads )的情况下,它具有利用 Applicative 的特殊实现计算的静态形式。

例如。下面的两个定义与正确的 JSON 表现相同,但 Applicative (使用 and )在错误情况下有更好的错误消息(例如,如果 barquux 都无效,则提及):

val applicativeReads: Reads[Foo] = (
(__ \ "bar").read[Int] and
(__ \ "quux").read[String]
)(Foo.apply _)

val monadicReads: Reads[Foo] = for {
bar <- (__ \ "bar").read[Int]
quux <- (__ \ "quux").read[String]
} yield Foo(bar, quux)

关于scala - JsResult - Monad 还是 Applicative?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189273/

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