Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created March 24, 2017 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/eaa919c7153817834fadb25580822d00 to your computer and use it in GitHub Desktop.
Save xuwei-k/eaa919c7153817834fadb25580822d00 to your computer and use it in GitHub Desktop.
libraryDependencies ++= Seq(
"org.scalaz" %% "scalaz-concurrent" % "7.2.10"
)
addCompilerPlugin("org.spire-math" % "kind-projector" % "0.9.3" cross CrossVersion.binary)
scalaVersion := "2.12.1"
import scalaz._
import scalaz.concurrent.Task
import scalaz.concurrent.Task._
object Main {
def main(args: Array[String]): Unit = {
taskSample()
}
def taskReaderSample(): Unit = {
val x = Parallel.parTraverse[
Kleisli[ParallelTask, Int, ?],
Kleisli[Task, Int, ?],
IList,
Int,
Int
](IList(1, 2, 3, 4)){
a => Kleisli[Task, Int, Int](s =>
Task{
println(s"start $s $a")
Thread.sleep(1000)
println(s"end $s $a")
a
}
)
}
println(x.unsafePerformSync)
}
def taskSample(): Unit = {
val x: Task[IList[Int]] = Parallel.parTraverse(IList(1, 2, 3, 4)){
a => Task{
println(s"start $a")
Thread.sleep(1000)
println(s"end $a")
a
}
}
println(x.unsafePerformSync)
}
}
package scalaz
import scalaz.concurrent.Task
import scalaz.concurrent.Task._
abstract class Parallel[M[_], F[_]](implicit val M: Monad[M], val F: Applicative[F]) {
def parallel: M ~> F
def sequential: F ~> M
}
object Parallel {
def apply[M[_], F[_]](implicit P: Parallel[M, F]): Parallel[M, F] = P
def parTraverse[F[_], M[_], T[_], A, B](ta: T[A])(f: A => M[B])(implicit
P: Parallel[M, F],
T: Traverse[T]
): M[T[B]] = {
import P._
sequential(T.traverse[F, A, B](ta)(a => parallel(f(a))))
}
implicit val task: Parallel[Task, ParallelTask] =
new Parallel[Task, Task.ParallelTask] {
override val parallel =
Lambda[Task ~> ParallelTask](Tags.Parallel(_))
override val sequential =
Lambda[ParallelTask ~> Task](Tags.Parallel.unwrap(_))
}
implicit def readerT[F[_], M[_], E](implicit P: Parallel[F, M]): Parallel[ReaderT[F, E, ?], ReaderT[M, E, ?]] = {
import P._
new Parallel[ReaderT[F, E, ?], ReaderT[M, E, ?]] {
override val parallel =
Lambda[ReaderT[F, E, ?] ~> ReaderT[M, E, ?]](_.transform(P.parallel))
override val sequential =
Lambda[ReaderT[M, E, ?] ~> ReaderT[F, E, ?]](_.transform(P.sequential))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment