什么是;美联社;在Scalaz做什么?
我正在查看scalaz的类型,并注意到方法什么是;美联社;在Scalaz做什么?,scala,scalaz,Scala,Scalaz,我正在查看scalaz的类型,并注意到方法ap /** Apply a function in the environment of the right of this disjunction. */ def ap[AA >: A, C](f: => AA \/ (B => C)): (AA \/ C) = f flatMap (ff => map(ff(_))) /**在此析取的右侧环境中应用函数*/ def ap[AA>:A,C](f:=>AA\/(B=>C)):(AA\/C)=
ap
/** Apply a function in the environment of the right of this disjunction. */
def ap[AA >: A, C](f: => AA \/ (B => C)): (AA \/ C) =
f flatMap (ff => map(ff(_)))
/**在此析取的右侧环境中应用函数*/
def ap[AA>:A,C](f:=>AA\/(B=>C)):(AA\/C)=
f平面图(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)
}
使用scalaz.\/
,通常在左侧放置异常
,在右侧放置“正确”返回类型ap
是一个函数,表示如果其中一个具有正确的类型,则应用此函数
for {
correctResponse <- ap(someEitherReturnMethod)
}
因为您可以flatMap
overfutures,所以您可以像上面一样链接一些方法,收集和传播错误
示例
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
}
def method1:Future[\/[异常,字符串]]
def method2(结果:字符串):Future[\/[异常,字符串]]
定义链示例:未来[\/[Exception,Int]={
为了{
firstResult谢谢!请解释一下ap是如何像EitherT一样工作的
?为什么一开始就要使用EitherT
?谢谢你的更新。我开始得到它了…假设我有f1:A=>Future[\/[Exception,B]
和f2:B=>Future[\/[Exception,C]]
我如何准确地用\/.ap
组合它们以获得f3:A=>未来[\/[Exception,C]
?@Michael你有map
和flatMap
。你能举一个组合f1
和f2
的例子来创建f3
(如上面评论中定义的那些函数)吗?@Michael更新了示例。
def someComplexThirdPartyApiCall: Future[\/[Exception, CorrectReturn]] = {
}
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
}