Created
June 8, 2013 02:04
-
-
Save patrick-premont/5733621 to your computer and use it in GitHub Desktop.
This code attempts to show one way asynchronous requests can be batched in a type safe manner.
This file contains 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
// This code attempts to show one way asynchronous requests can be batched in a type safe manner. | |
object BatchableRequests { | |
sealed trait Request[A] { | |
def serialize(): String | |
def deserialize(s: String): Option[(A, String)] | |
def pair[B](b: Request[B]): Request[(A, B)] = RequestPair(this, b) | |
} | |
case class RequestPair[A, B](a: Request[A], b: Request[B]) extends Request[(A, B)] { | |
def serialize() = a.serialize + b.serialize | |
def deserialize(s: String) = | |
for { | |
(av, rest) <- a.deserialize(s) | |
(bv, rest2) <- b.deserialize(rest) | |
} yield ((av, bv), rest2) | |
} | |
case class SampleRequest1(a: Int) extends Request[Either[String, Boolean]] { | |
def serialize = ??? | |
def deserialize(s: String) = ??? | |
} | |
case class SampleRequest2(a: String, b: String) extends Request[Int] { | |
def serialize = ??? | |
def deserialize(s: String) = ??? | |
} | |
def call[A](r: Request[A]): Future[Either[String, A]] = { | |
def asyncCall(s: String) : Future[String] = ??? | |
asyncCall(r.serialize()).map(r.deserialize(_) | |
.fold[Either[String, A]](Left("Badly formatted response"))(o => Right(o._1))) | |
} | |
val a = call(SampleRequest1(10) pair SampleRequest2("x", "y") pair SampleRequest1(2)) | |
// a's infered type: Future[Either[String,((Either[String,Boolean], Int), Either[String,Boolean])]] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment