Last active
October 14, 2016 05:28
-
-
Save 13h3r/df206edc3360ecfdbd2a9cf36bcb2a7a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import cats.Functor | |
| import cats.data._ | |
| import scala.concurrent.duration.Duration | |
| import scala.concurrent.{Await, Future} | |
| import scala.util.Random | |
| object XXX extends App { | |
| import cats.data.{Xor, XorT} | |
| import cats.instances.future._ | |
| import scala.concurrent.ExecutionContext.Implicits.global | |
| case class Result(i: Option[Int], s: Option[String]) | |
| type S[T] = StateT[Future, Result, T] | |
| type StepResult[T] = XorT[S, Any, T] | |
| implicit val sFunctor = new Functor[S] { | |
| override def map[A, B](fa: S[A])(f: (A) => B): S[B] = fa.map(f) | |
| } | |
| def checkResult[T](t: T): Xor[T, T] = { | |
| if (System.nanoTime() % 10 == 0) Xor.Left(t) | |
| else Xor.Right(t) | |
| } | |
| def step[T](f: Result => Future[(Result, Xor[Any, T])]): StepResult[T] = { | |
| XorT.apply[S, Any, T]( | |
| StateT[Future, Result, Xor[Any, T]](f) | |
| ) | |
| } | |
| def getInt() = step { s => | |
| Future.successful(Random.nextInt()) | |
| .map(checkResult) | |
| .map { x => | |
| (s.copy(i = x.toOption), x) | |
| } | |
| } | |
| def getString(i: Int) = step { s => | |
| Future.successful(i + "haha") | |
| .map(checkResult) | |
| .map { x => | |
| (s.copy(s = x.toOption), x) | |
| } | |
| } | |
| def r = for { | |
| i <- getInt() | |
| s <- getString(i) | |
| } yield s | |
| 1 to 100 foreach { _ => | |
| val x1 = Await.result(r.fold(identity, identity).runS(Result(None, None)), Duration.Inf) | |
| println(x1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment