10

我有一组返回不同类型的方法:

Either[ErrorResponse, X]
Future[Either[ErrorResponse, X]]
Option[ErrorResponse]

这些方法需要先前方法的结果来执行它们的计算。方法:

type Parameters = Map[String, String]

// allows me to flatmap on an either
implicit def toRightProjection[Failure, Success](e: Either[Failure, Success]) =
  e.right

// converts anything to a future
implicit def toFuture[T](t: T) =
  Future.successful(t)

// retrieves the request paramters from the given request
def requestParameters(request: RequestHeader): Either[ErrorResponse, Parameters] = ???

// retrieves the response type from the given parameters
def responseType(p: Parameters): Either[ErrorResponse, String] = ???

// retrieves the client id from the given parameters
def clientId(p: Parameters): Either[ErrorResponse, String] = ???

// retrieves the client using the given client id
def client(clientId: String): Future[Either[ErrorResponse, Client]] = ???

// validates the response type of the client
def validateResponseType(client: Client, responseType: String): Option[ErrorResponse] = ???

我可以将它们与以下内容连接在一起以进行理解(请注意,我写下了一些类型以阐明计算的特定部分的内容)。

val result: Either[ErrorResponse, Future[Either[ErrorResponse, Client]]] =
  for {
    parameters <- requestParameters(request)
    clientId <- clientId(parameters)
    responseType <- responseType(parameters)
  } yield {
    val result: Future[Either[ErrorResponse, Either[ErrorResponse, Client]]] =
      for {
        errorOrClient <- client(clientId)
        client <- errorOrClient
      } yield validateResponseType(client, responseType).toLeft(client)

    result.map(_.joinRight)
  }

val wantedResult: Future[Either[ErrorResponse, Client]] =
  result.left.map(Future successful Left(_)).merge

上面的代码很乱,我觉得这可以做不同的事情。我读到了 monads 和 monad 转换器。这些概念对我来说是非常新的,我无法理解它。

大多数示例仅处理两种类型的结果:Either[X, Y]Future[Either[X, Y]]. 我仍然觉得很难绕开它。

我怎样才能写一个漂亮而干净的理解来代替上面的?

这样的事情会很棒(我不确定这是否可能):

val result: Future[Either[ErrorResponse, Client]] =
  for {
    parameters <- requestParameters(request)
    clientId <- clientId(parameters)
    responseType <- responseType(parameters)
    client <- client(clientId)
    _ <- validateResponseType(client, responseType)
  }
4

3 回答 3

13

好的,这是我的尝试:

import scalaz._, Scalaz._

implicit val futureMonad = new Monad[Future] {
  override def point[A](a: ⇒ A): Future[A] = future(a)

  override def bind[A, B](fa: Future[A])(f: A ⇒ Future[B]): Future[B] =
    fa.flatMap(f)
}

import EitherT._
val result: EitherT[Future, ErrorResponse, Client] =
  for {
    parameters <- fromEither(Future(requestParameters(request)))
    clientId <- fromEither(Future(clientId(parameters)))
    responseType <- fromEither(Future(responseType(parameters)))
    client <- fromEither(client(clientId))
    response <- fromEither[Future, ErrorResponse, Client](Future(validateResponseType(client, responseType).toLeft(client)))
  } yield response

val x: Future[\/[ErrorResponse, Client]] = result.run
于 2013-10-08T22:33:12.707 回答
2

scala.util.Either不是 Monad,但 scalaz 库有一个很好的实现。

object Test extends ToIdOps {

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

implicit val FutureFunctor = new Functor[Future] {
    def map[A, B](a: Future[A])(f: A => B): Future[B] = a map f
}

implicit val FutureMonad = new Monad[Future] {
  def point[A](a: => A): Future[A] = Future(a)
  def bind[A, B](fa: Future[A])(f: (A) => Future[B]): Future[B] = fa flatMap f
}
def someMethod: Future[\/[InvalidData, ValidData]] = {
   // things went well
   ValidData.right // this comes from ToIdOps
   // or something went wrong
   InvalidData.left
}
def someOtherMethod: Future[\/[InvalidData, ValidData]] // same as above
val seq = for {
  d <- EitherT(someMethod)
  y <- EitherT(someOtherMethod)
} yield { // whatever}
// you can now Await.result(seq.run, duration)
// you can map or match etc with \/- and -\/
val result = seq.run map {
   case -\/(left) => // invalid data
   case \/-(right) => // game on
}
}
于 2013-10-08T22:44:11.433 回答
0

没有真正干净的方法可以对多种 monad 类型进行理解。在 ScalaZ 中有 OptionT 可能会有所帮助,值得一试。您还可以将您的 Eithers 转换为 Options 或相反的方式,并且能够少一点混乱。第三种选择可能是创建自己的包装器,将 Future[Either|Option] 组合到同一个 monad 中,然后对其进行理解。

作为参考,我最近在播放框架邮件列表上询问了同样的问题,并在回复中获得了一些很好的链接:https ://groups.google.com/d/topic/play-framework/JmCsXNDvAns/discussion

于 2013-10-08T20:58:43.203 回答