Skip to content

Instantly share code, notes, and snippets.

@LukaJCB
Created May 22, 2017 17:55
Show Gist options
  • Save LukaJCB/b1687855706ad2beb527ae4ebe62b723 to your computer and use it in GitHub Desktop.
Save LukaJCB/b1687855706ad2beb527ae4ebe62b723 to your computer and use it in GitHub Desktop.
SimpleIOMonad
class IO[+T](run: => T) {
def map[R](f: T => R): IO[R] = {
IO(f(run))
}
def flatMap[R](f: T => IO[R]): IO[R] = {
IO(f(run).unsafeRun())
}
def unsafeRun(): T = run
}
object IO {
def apply[T](run: => T) = new IO(run)
def log(a: Any): IO[Unit] = IO {
println(a)
}
def random: IO[Double] = IO {
Math.random()
}
def randomInt: IO[Int] = {
random map (n => (n * 100).toInt)
}
}
val program = for {
rnd <- IO.randomInt
_ <- IO.log(rnd)
rnd2 <- IO.randomInt
_ <- IO.log(rnd2 - rnd)
} yield ()
program.unsafeRun()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment