Skip to content

Instantly share code, notes, and snippets.

@PavelZaytsev
Created December 2, 2018 09:03
Show Gist options
  • Save PavelZaytsev/842148cb508f9809bd39f4de71c06cbe to your computer and use it in GitHub Desktop.
Save PavelZaytsev/842148cb508f9809bd39f4de71c06cbe to your computer and use it in GitHub Desktop.
import scala.concurrent.ExecutionContext
case class Async[A, E](cb: (A => E) => E)
object Async {
def run[A, E](async: Async[A, E])(
implicit ec: ExecutionContext): (A => E) => E = async match {
case Async(callback) =>
f =>
callback(f)
}
// a bit tricky but doable:
def map[A, E, B](a: Async[A, E])(f: A => B)(
implicit ec: ExecutionContext): Async[B, E] = {
Async { callback =>
run(a)(ec) { input: A =>
val lifted: A => Async[B, E] = input => pure(f(input))
val asyncB: Async[B, E] = lifted(input)
run(asyncB)(ec)(callback)
}
}
}
def pure[A, E](a: A): Async[A, E] = Async(x => x(a))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment