cats scala中的monad变换器

monad transformers in cats scala

我正在尝试学习 scala cats 库。所以我对函数式编程完全陌生。

请帮我从下面的示例函数中提取值:

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

我认为,下面是最简单的方法:

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

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

您也可以使用纯函数将 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