: A, C](f: => AA\/(B => C))-6ren">
gpt4 book ai didi

scala - Scalaz 中\/的 "ap"有什么作用?

转载 作者:行者123 更新时间:2023-12-04 12:32:05 25 4
gpt4 key购买 nike

我在看 disjunction scalaz 的类型,我注意到方法 ap
/** 在这个析取权的环境中应用一个函数。 */
def ap[AA >: A, C](f: => AA\/(B => C)): (AA\/C) =
f flatMap (ff => map(ff(_)))

我想我明白它的作用了。现在我想知道何时以及为什么应该实际使用它?有没有使用这个的例子ap功能 ?

最佳答案

您正在寻找的分离:

import scalaz.{ \/, -\/ \/-, EitherT }
import scalaz.syntax.ToIdOps

object Testing extends ToIdOps // left and right methods come from there {
// say you have the following method
def someMethod(flag: Boolean): \/[Exception, SomeObject] {
if (flag) someObj.right else new Exception("this is a sample").left
}
}

// pattern matching
val x = someMethod match {
case \/-(right) => // this is someObject
case -\/(err) => // deal with the error
}

// catamorphism
def methodThatDealsWithObj(obj: someObject)
def methodThatDealsWithErr(err: Exception)
someMethod.fold(methodThatDealsWithObj)(methodThatDealsWithErr)

// for comprehensions
// ap behaves just like EitherT.
for {
correctResponse <- EitherT(someMethod)
}

更新

了解如何 EitherTap有效,想到一个 Option ,其中有 SomeNone和潜在的匹配。与 Option ,你会这样做:
for {
a <- someOption
} yield ..

scalaz.\/ ,你通常会放一个 Exception左侧和右侧的“正确”返回类型。 ap是一个函数,表示如果两者都具有正确的类型,则应用它。
for {
correctResponse <- ap(someEitherReturnMethod)
}

用例

我能想到的最常见的事情是我最喜欢使用它们的地方是复杂的异步流,例如 OAuth1 或 OAuth2,我关心的是细粒度的错误链接。

您可以使用 \/作为 Future 的返回:
def someComplexThirdPartyApiCall: Future[\/[Exception, CorrectReturn]] = {
}

因为你可以 flatMap在 future 上,您可以链接上述几种方法,收集和传播错误。

示例
  def method1: Future[\/[Exception, String]]
def method2(result: String): Future[\/[Exception, String]]

def chainExample: Future[\/[Exception, Int]] = {
for {
firstResult <- EitherT(method1)
secondResult <- EitherT(method2(firstResult))
} yield secondResult.toInt
}

关于scala - Scalaz 中\/的 "ap"有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22483365/

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