Scala猫,用ReaderT编写阅读器
下面是函数的一个小组合,所有函数都返回Scala猫,用ReaderT编写阅读器,scala,composition,monad-transformers,scala-cats,reader-monad,Scala,Composition,Monad Transformers,Scala Cats,Reader Monad,下面是函数的一个小组合,所有函数都返回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"))
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))
})
def f1:Reader[Map[String,String], Boolean] = Reader(_ => true)
现在我必须编写
Reader
,它正是ReaderT[Id,…]
和Reader[FailFast,…]
就像你提到的Reader[A,B]
就是ReaderT[Id,A,B]
(它本身只是Kleisli[Id,A,B]
的一个类型别名)
由于您使用的是cats,因此有一个名为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))
})
val Id2FailFast=new(Id~>FailFast){
def应用[T](f:Id[T]):快速失效[T]=右侧(f)
}
f1.mapK(Id2FailFast).flatMap(b1=>{
如果(b1)
为了{
b2正如您所提到的Reader[A,B]
只是ReaderT[Id,A,B]
(它本身只是Kleisli[Id,A,B]
的一个类型别名)
由于您使用的是cats,因此有一个名为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))
})
val Id2FailFast=new(Id~>FailFast){
def应用[T](f:Id[T]):快速失效[T]=右侧(f)
}
f1.mapK(Id2FailFast).flatMap(b1=>{
如果(b1)
为了{
b2谢谢。我尝试使用此方法,但出现了一些错误,使用了mapF而不是mapK,并且没有Id2FailFast helper函数无法将其正确转换。我必须应用到您的解决方案中的唯一更改是将f类型从Id更改为Id[T]。如果没有它,我会遇到一个错误:类型Id采用类型参数def apply[T](f:Id):FailFast[T]=正确的(f)谢谢。我尝试使用这种方法,但由于一些错误,使用了mapF而不是mapK,并且没有Id2FailFast帮助函数无法将其正确转换。我必须应用到解决方案中的唯一更改是将f类型从Id更改为Id[T]没有它,我得到了一个错误:type Id接受类型参数def apply[T](f:Id):FailFast[T]=Right(f)