结合期货,Eithers和期权进行理解

时间:2013-10-08 19:53:49

标签: scala

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

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

上面的代码非常混乱,我觉得这可以用不同的方式完成。我读过monad和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)
  }

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
}
}

答案 2 :(得分:0)

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

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

相关问题