简体   繁体   English

猫斯卡拉单子变压器

[英]monad transformers in cats scala

i am trying to learn scala cats library. 我正在尝试学习斯卡拉猫图书馆。 So i am completely new to functional programming. 所以我对函数式编程完全陌生。

Please help me to extract value from below example function : 请帮助我从下面的示例函数中提取值:

import cats._
import cats.data._
import cats.syntax._
import cats.implicits._
import cats.functor._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
//import cats.syntax.applicative._


//Here i added test functions to return Either[List[String], A] where left is collecting error list.

case class User(name:String)
case class Users(ppl:List[User])

val testUsers = List(User("test1"), User("test2"))

val func0:Future[Either[List[String], Users]] = () => Future.successful(testUsers.asRight[List[String]])
val func1:(Users => Either[List[String], User]) = (users:Users) => users.ppl(0).asRight[List[String]]

//How to make this function to return Future[Either[List[String], User]] = ???
val res:Future[Either[List[String], Either[List[String], User]]] = EitherT(func0).map(func1).value

You could also use the pure function to lift the result of func0 into EitherT and then combined it all together in a for-comprehension. 您还可以使用pure函数将func0的结果提升到EitherT中,然后将其全部合并在一起以产生理解。

import cats.data._
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import cats.instances.future._

case class User(name: String)

case class Users(ppl: List[User])

val testUsers = List(User("test1"), User("test2"))

val func0: Future[Either[List[String], Users]] = () => Future.successful(testUsers.asRight[List[String]])
val func1: (Users => Either[List[String], User]) = (users: Users) => users.ppl.head.asRight[List[String]]

type ListEither[A] = EitherT[Future, List[String], A]

val res: Future[Either[List[String], User]] = for {
  f0 <- func0.pure[ListEither]
  f1 <- EitherT(f0).map(func1).value
} yield f1

I think, below is an easiest way: 我认为,以下是最简单的方法:

val testUser: Future[Either[List[String], Either[List[String], User]]] = ???

val testUser1: Future[Either[List[String], User]] = testUser.map(_.flatMap(identity))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM