Created
August 9, 2016 22:26
-
-
Save jdegoes/7cc7e7aacd032773f3c24123d0d486d4 to your computer and use it in GitHub Desktop.
A pedagogical implementation of the IO monad in Scala in 14 LOC
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
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] = | |
IO(() => IO.tryIO(unsafePerformIO()).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