Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save monkey-codes/84671c4c518bad81fd574608831ced45 to your computer and use it in GitHub Desktop.
Simple IO monad that can cause stack overflow. Implementation without trampolining
interface IO<A> {
companion object {
fun <A> unit(a: () -> A) = object : IO<A> {
override fun run(): A = a()
}
operator fun <A> invoke(a: () -> A) = unit(a)
}
fun run(): A
fun <B> flatMap(f: (A) -> IO<B>): IO<B> =
object : IO<B> {
override fun run(): B = f(this@IO.run()).run()
}
}
fun stdin() = IO { readLine().orEmpty() }
fun stdout(msg: String) = IO { println(msg) }
fun main() {
val echo = stdin().flatMap(::stdout)
echo.run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment