加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

斯卡拉 – JsResult – Monad或Applicative?

发布时间:2020-12-16 08:57:43 所属栏目:安全 来源:网络整理
导读:我对Monad和Applicative之间的区别之一的理解是,flatMap可用于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
我对Monad和Applicative之间的区别之一的理解是,flatMap可用于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-comprehension是flatMap的语法糖,JsResult如何同时成为Applicative和Monad?

解决方法

Monad是Applicative的子类. Applicative的 apply比flatMap弱.因此,apply可以用flatMap实现.

但是,在JsResult(或实际的Reads)案例中,它具有特殊的实现,它利用了Applicative计算的静态形式.

例如.下面的两个定义与正确的JSON等效,但Applicative(使用和)在错误的情况下有更好的错误消息(例如,如果bar和quux都无效,则提及:)

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读