-
-
Save mvillafuertem/e565ef9230019d48646cff88ba515bf2 to your computer and use it in GitHub Desktop.
parTraverse with a limit of N using a Semaphore
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.Traverse | |
import cats.effect._ | |
import cats.effect.concurrent.Semaphore | |
import cats.temp.par._ | |
import cats.syntax.all._ | |
import scala.concurrent.duration._ | |
object Main extends IOApp { | |
import ParTask._ | |
def putStrLn[A](a: A): IO[Unit] = IO(println(a)) | |
override def run(args: List[String]): IO[ExitCode] = { | |
import cats.instances.list._ | |
parTraverseN(3, List.range(1, 10))(x => putStrLn(x) *> IO.sleep(1.second)).as(ExitCode.Success) | |
} | |
} | |
object ParTask { | |
def parTraverseN[F[_]: Concurrent: Par, G[_]: Traverse, A, B]( | |
n: Int, | |
ga: G[A] | |
)(f: A => F[B]) = | |
Semaphore[F](n).flatMap { s => | |
ga.parTraverse(a => s.withPermit(f(a))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment