如何使用 EitherT 删除带有 Future 和 Either 的样板文件

How to use EitherT to remove boilerplate with Future and Either

我需要一个与 Future\/ 一起使用的组合器,我认为 EitherT 将有助于删除样板文件:

经过一番尝试,我想出了

  type FutureEitherT[A] = EitherT[Future, String, A]

  def toKleisliEitherTFromDisjunction[A](f: Kleisli[Future, Context,String \/ A]) = Kleisli[FutureEitherT, Context, A] { ctx => EitherT(f(ctx)) }

  def h[A, B](f: Kleisli[Future, Context, String \/ A], g: A => Kleisli[Future, Context, String \/ B]) =
    for {
      a <- toKleisliEitherTFromDisjunction(f)
      b <- toKleisliEitherTFromDisjunction(g(a))
    } yield b

借助这个

  type FutureEitherT[A] = EitherT[Future, String, A]

  def h[A, B](f: Kleisli[Future, Context, String \/ A], g: A => Kleisli[Future, Context, String \/ B]) =
    for {
      a <- f.mapK[FutureEitherT, A](EitherT.eitherT)
      b <- g(a).mapK[FutureEitherT, B](EitherT.eitherT)
    } yield b