Scala-cats,用ReaderT编写Reader

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

这是一个很小的函数组合,所有函数都返回ReaderT

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

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

  def fc:ReaderT[FailFast, Map[String,String], Boolean] =
    f1.flatMap( b1 => {
      if (b1)
        for {
          b2 <- f2
          b3 <- f3
          b4 <- f4
        } yield b4
      else ReaderT(_ => Right(true))
    })

如果fc将返回f1,而不是Reader,如何实施ReaderT

def f1:Reader[Map[String,String], Boolean] = Reader(_ => true)

现在我必须组成Reader,这正是ReaderT[Id, ...]Reader[FailFast, ...]

scala composition monad-transformers scala-cats reader-monad
1个回答
2
投票

正如你所提到的,Reader[A, B]只是ReaderT[Id, A, B](它本身只是Kleisli[Id, A, B]的类型别名)。

由于您使用的是猫,因此有一种名为mapK的方法映射到ReaderT的第一个类型参数,您只需要为转换提供FunctionK/~>实例。所以在你的情况下,它看起来像这样:

val Id2FailFast = new (Id ~> FailFast) {
  def apply[T](f: Id[T]): FailFast[T] = Right(f) 
}

f1.mapK(Id2FailFast).flatMap( b1 => {
  if (b1)
    for {
      b2 <- f2
      b3 <- f3
      b4 <- f4
    } yield b4
  else ReaderT(_ => Right(true))
})

可能还有一些其他的重构可以进一步清理它,比如使用EitherT但是因为它看起来像是一个人为的例子,所以我将把它作为读者的练习。

© www.soinside.com 2019 - 2024. All rights reserved.