-
-
Save monkey-codes/84671c4c518bad81fd574608831ced45 to your computer and use it in GitHub Desktop.
Simple IO monad that can cause stack overflow. Implementation without trampolining
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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