gpt4 book ai didi

scala - 什么是 Applicative Builder

转载 作者:行者123 更新时间:2023-12-04 14:55:03 24 4
gpt4 key购买 nike

我是 Scala 和功能新手,正在尝试学习应用程序。

val o1 = Some(1)
val o2 = Some(2)
val o3 = Some(3)
val result = (o1 |@| o2 |@| o3) {_ + _ + _}
关于 Applicatives 和 Functors 的读物非常好 here
根据这篇博客,

Operator |@| is the product operation



combining your applicatives into a product by using |@| results in anApplicativeBuilder which takes a function to perform on the product(since product + map is a very common use case)


我发现很难理解博客中的上述两个陈述。
任何在 Scala 中使用代码的示例来理解这一点都会有所帮助。

最佳答案

我认为这篇文章的关键是这句话,这应该有助于推理应用仿函数:

Hey, so you got your function wrapped into a bit of a context, huh? Not to worry, I know how to apply those kind of wrapped functions



Applicative 提供了一种将包装在上下文中的函数应用于其他包装值的方法。
|@|和底层类型 ApplicativeBuilder只是通过 DSL 构建这些应用程序的 scalazs 方式。

从文档(强调我的):

Whereas a scalaz.Functor allows application of a pure function to a value in a context, an Applicative also allows application of a function in a context to a value in a context (ap)



Operator |@| is the product operation



通过“乘积操作”,OP 意味着它是采用两个值并将它们包装在 ApplicativeBuilder 中的操作。 .
|@|是一个方法,在调用时返回 ApplicativeBuilder 的实例:
final def |@|[B](fb: F[B]) = new ApplicativeBuilder[F, A, B] {
val a: F[A] = self
val b: F[B] = fb
}

哪里 F是一阶类型,具有 Apply实例定义:
implicit val F: Apply[F]

哪里 Apply只是一个 Applicative没有 point方法。

combining your applicatives into a product by using |@| results in an ApplicativeBuilder which takes a function to perform on the product (since product + map is a very common use case)



如果您以您的示例为例,将其简化为两个 Option[Int] s:
import scalaz.Scalaz._

val o1 = 1.some
val o2 = 1.some
val result: ApplicativeBuilder[Option, Int, Int] = o1 |@| o2
val finalRes: Option[Int] = result.apply(_ + _)

我们:
  • 申请 |@|Option[Int] 的两个实例并取回 ApplicativeBuilder[Option, Int, Int] . Option这是我们的 F ,它有一个 Apply 的实例.
  • 取回构建器的实例后,我们调用它的 apply方法。我们为其提供了形状函数 Int -> Int它给了我们一个 Option[Int] ,这意味着我们仍然在上下文中,但是操作应用于我们的值。
  • 关于scala - 什么是 Applicative Builder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152882/

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