Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save monkey-codes/16d8107563638d78b081bd013ced83a9 to your computer and use it in GitHub Desktop.
IO Monad
sealed class IO<A> {
companion object {
fun <A> unit(a: A): IO<A> = Suspend { a }
}
fun <B> flatMap(f: (A) -> IO<B>): IO<B> = FlatMap<A, B>(this, f)
fun <B> map(f: (A) -> B): IO<B> = flatMap { a -> Return(f(a)) }
}
data class Return<A>(val a: A) : IO<A>()
data class Suspend<A>(val resume: () -> A) : IO<A>()
data class FlatMap<A, B>(val sub: IO<A>, val f: (A) -> IO<B>) : IO<B>()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment