Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Created November 27, 2019 12:03
Show Gist options
  • Save rbobillot/387618787fca24b293f20bcff1c1d4ba to your computer and use it in GitHub Desktop.
Save rbobillot/387618787fca24b293f20bcff1c1d4ba to your computer and use it in GitHub Desktop.
sealed trait IO[+A] {
def unsafeRunSync(): A
def flatMap[B](f: A => IO[B]): IO[B] = IO.FlatMap(this, f)
def map[B](f: A => B): IO[B] = flatMap(f andThen IO.pure _)
// -------------------- Sync Maniputation Methods ----------------------------
def attempt: Either[Throwable, A] = scala.util.Try(unsafeRunSync()).toEither
// -------------------- Async Maniputation Methods ---------------------------
}
object IO {
// ---------------------------- Init ATDs ------------------------------------
private case class Apply[A](f: () => A) extends IO[A] {
override def unsafeRunSync(): A = f()
}
private case class Pure[A](f: () => A) extends IO[A] {
override def unsafeRunSync(): A = f()
}
private case class Error[A](t: Throwable) extends IO[A] {
override def unsafeRunSync(): A = throw t
}
// ------------------------ Manipulation ATDs --------------------------------
private case class FlatMap[A, B](io: IO[A], f: A => IO[B]) extends IO[B] {
override def unsafeRunSync(): B = f(io.unsafeRunSync()).unsafeRunSync()
}
// -------------------------- Init Method ------------------------------------
def apply[A](a: => A): IO[A] = Apply(() => a)
def pure[A](a: A): IO[A] = Pure(() => a)
def error[A](t: Throwable): IO[A] = Error[A](t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment