Skip to content

Instantly share code, notes, and snippets.

@Jacoby6000
Forked from jdegoes/IO.scala
Last active January 19, 2018 17:16
Show Gist options
  • Save Jacoby6000/6d9b85776aa37261b2c71ce66dfa70f7 to your computer and use it in GitHub Desktop.
Save Jacoby6000/6d9b85776aa37261b2c71ce66dfa70f7 to your computer and use it in GitHub Desktop.
A pedagogical implementation of the IO monad in Scala in 14 LOC
case class IO[A](unsafePerformIO: () => A) {
def map[B](ab: A => B): IO[B] = IO(() => ab(unsafePerformIO()))
def flatMap[B](afb: A => IO[B]): IO[B] =IO(() => afb(unsafePerformIO()).unsafePerformIO())
def tryIO(ta: Throwable => A): IO[A] =
val attempt = IO(() => IO.tryIO(unsafePerformIO()) // lift IO[A] to IO[Either[Throwable,A]]
attempt.unsafePerformIO() match {
case Left(t) => ta(t)
case Right(a) => a
})
}
object IO {
def point[A](a: => A): IO[A] = IO(() => a)
def tryIO[A](a: => A): IO[Either[Throwable, A]] =
IO(() => try { Right(a) } catch { case t : Throwable => Left(t) })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment