Scala-Cats:用应用效果组合monadic

问题描述 投票:0回答:1

以下是返回ReaderT的函数定义:

  def f1:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
  def f2:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Left(List("d")))
  def f3:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
  def f4:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))

我想把它们结合起来。 f1f2被用作monadic效果。但必须积累f3f4的结果。我尝试实现看起来像这样的东西:

  def fc:ReaderT[FailFast, Map[String,String], Boolean] =
    f1.flatMap( b1 => {
      if (b1)
        for {
          b2 <- f2
          b3 <- Semigroupal.tuple2[FailSlow, Boolean, Boolean](
            f3, // how to convert it to validated here without run?
            f4  // how to convert it to validated here without run?
          ).toEither
        } yield b3
      else ReaderT(_ => Right(true))
    })

如果存在多个选项,请同时提供

scala validation monads composition scala-cats
1个回答
0
投票

尝试

import cats.instances.either._
import cats.instances.list._

type FailSlow[A] = Validated[List[String], A]
type FailFast[A] = Either[List[String], A]

def fc:ReaderT[FailFast, Map[String,String], (Boolean, Boolean)] =
  f1.flatMap( b1 => {
    if (b1)
      for {
        b2 <- f2
        b3 <- Semigroupal.tuple2(
          f3.mapF(Validated.fromEither),
          f4.mapF(Validated.fromEither)
        ).mapF(_.toEither)
      } yield b3
    else ReaderT(_ => Right(true, true))
  })
© www.soinside.com 2019 - 2024. All rights reserved.