简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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