简体   繁体   English

\\ / Scalaz中的“ap”有什么作用?

[英]What does “ap” of \/ in Scalaz do?

I am looking at disjunction type of scalaz and I noticed method ap 我在看脱节型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(_)))

I guess I understand what it does. 我想我明白它的作用。 Now I wonder when and why one should actually use it ? 现在我想知道何时以及为什么要实际使用它? Are there any examples of using this ap function ? 有没有使用这个ap功能的例子?

The disjunction you are looking for: 您正在寻找的分离:

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)
}

Update 更新

To understand how EitherT and ap works, think of an Option , which has Some and None and potential matches. 要了解EitherTap工作原理,请考虑一个Option ,它有SomeNone以及潜在的匹配。 With an Option , you would do: 使用Option ,您可以:

for {
  a <- someOption
} yield ..

With scalaz.\\/ , you usually put an Exception on the left and a "correct" return type on the right. 使用scalaz.\\/ ,您通常在左侧放置一个Exception ,在右侧放置一个“正确”的返回类型。 ap is a function that says apply this if the either has the correct type. ap是一个函数,如果要么具有正确的类型,则应用此函数。

for {
  correctResponse <- ap(someEitherReturnMethod)
}

Use cases 用例

The most common things I can think off where I use them avidly is complex asynchronous flows, such as OAuth1 or OAuth2, where I care about fine grained chaining of errors. 我能想到的最常见的事情就是复杂的异步流程,例如OAuth1或OAuth2,我关心错误的细粒度链接。

You can use \\/ as the return of a Future : 您可以使用\\/作为Future的回报:

def someComplexThirdPartyApiCall: Future[\/[Exception, CorrectReturn]] = {
}

Because you can flatMap over futures, you can chain a couple methods like the above, collect and propagate errors. 因为你可以对期货进行flatMap ,你可以链接一些像上面这样的方法,收集和传播错误。

Example

  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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM