class IO[A](sideEffect: => A) {
lazy val run: A = sideEffect
def map[B](f: A => B): IO[B] =
new IO(f(run))
def flatMap[B](f: A => IO[B]): IO[B] =
new IO(f(run).run)
}
val program: IO[Unit] =
for {
<- new IO(print("Type something: "))
_ <- new IO(readLine())
in = "You typed: " + in
out <- new IO(println(out))
_ } yield ()
println("Running program...")
.run program
This file is literate Scala, and can be run using Codedown:
$ curl https://earldouglas.com/posts/type-classes/io.md |
codedown scala > script.scala
$ scala -nc script.scala
Type something: Hello, IO!
You typed: Hello, IO!