Created
May 22, 2017 17:55
-
-
Save LukaJCB/b1687855706ad2beb527ae4ebe62b723 to your computer and use it in GitHub Desktop.
SimpleIOMonad
This file contains 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
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