Skip to content

Instantly share code, notes, and snippets.

@monkey-codes
Created June 9, 2023 23:31
Show Gist options
  • Select an option

  • Save monkey-codes/1dea7faab8a132074a84fade9001f2ac to your computer and use it in GitHub Desktop.

Select an option

Save monkey-codes/1dea7faab8a132074a84fade9001f2ac to your computer and use it in GitHub Desktop.
IO monad interpreter
object Interpreter {
tailrec fun <A> run(
io: IO<A>
): A =
when (io) {
is Return -> io.a
is Suspend -> io.resume()
is FlatMap<*, *> -> {
val x = io.sub as IO<A>
val f = io.f as (A) -> IO<A>
when (x) {
is Return -> run(f(x.a))
is Suspend -> run(f(x.resume()))
is FlatMap<*, *> -> {
val g = x.f as (A) -> IO<A>
val y = x.sub as IO<A>
run(y.flatMap { a: A -> g(a).flatMap(f) })
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment