Last active
November 18, 2015 11:59
-
-
Save Centaur/d65fc0dc01612a3babc7 to your computer and use it in GitHub Desktop.
HList Sequence
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 scalaz.{idInstance => _, _} | |
import std.scalaFuture._ | |
import syntax.applicative._ | |
import shapeless._ | |
import UnaryTCConstraint.*->* | |
import poly._ | |
import ops.hlist._ | |
object HListSequence { | |
object applicativeFolder extends Poly2 { | |
implicit def caseApplicative[A, B <: HList, F[_]](implicit app: Applicative[F]) = at[F[A], F[B]] { | |
(a, b) => app.ap(a)(app.map(b)(bb => (_: A) :: bb)) | |
} | |
} | |
def sequence[F[_] : Applicative, L <: HList : *->*[F]#λ, M <: HList](l: L)(implicit folder: RightFolder[L, F[HNil], applicativeFolder.type]) = | |
l.foldRight(implicitly[Applicative[F]].point(HNil: HNil))(applicativeFolder) | |
} | |
object Main { | |
import scala.concurrent.{duration, Await, Future} | |
import concurrent.ExecutionContext.Implicits.global | |
import duration._ | |
import HListSequence._ | |
val a = Future(1) | |
val b = Future("a") | |
val c = Future('b') | |
val tuple = (a, b, c) | |
val result: Future[(Int, String, Char)] = sequence(HList(tuple)).map(_.tupled) | |
def main(args: Array[String]) { | |
assert(Await.result(result, 1.second) == (1, "a", 'b')) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment