Skip to content

Instantly share code, notes, and snippets.

@purefn
Created March 18, 2011 00:01
Show Gist options
  • Save purefn/875391 to your computer and use it in GitHub Desktop.
Save purefn/875391 to your computer and use it in GitHub Desktop.
A start on a package for doing monadic IO in scala
package object io {
sealed trait IO[A] {
def unsafePerformIO: A
}
object IO {
def apply[A](a: => A): IO[A] = new IO[A] {
def unsafePerformIO = a
}
}
implicit val IOMonad = new Monad[IO] {
def pure[A](a: => A): IO[A] = IO(a)
def bind[A,B](a: IO[A], f: A => IO[B]): IO[B] = IO {
implicitly[Monad[Function0]].bind(() => a.unsafePerformIO, (x:A) => () => f(x).unsafePerformIO)()
}
}
def bracket[A,B,C](init: IO[A], fin: A => IO[B], body: A => IO[C]): IO[C] =
for { a <- init
c <- body(a)
_ <- fin(a) }
yield c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment