Skip to content

Instantly share code, notes, and snippets.

@nomisRev
Created May 23, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nomisRev/13eb7e68a943c3dde210ad7d075a2611 to your computer and use it in GitHub Desktop.
Save nomisRev/13eb7e68a943c3dde210ad7d075a2611 to your computer and use it in GitHub Desktop.
Console Effect handler
import arrow.core.continuations.EffectScope
import arrow.core.continuations.effect
object EndOfLine
interface Console {
context(EffectScope<EndOfLine>)
suspend fun read(): String
suspend fun String.write(): Unit
suspend fun String.writeLine(): Unit
companion object Default : Console {
context(EffectScope<EndOfLine>)
override suspend fun read(): String = readlnOrNull() ?: shift(EndOfLine)
override suspend fun String.write() = print(this)
override suspend fun String.writeLine() = println(this)
}
}
context(Console, EffectScope<EndOfLine>, EffectScope<String>)
tailrec suspend fun program(): Unit {
"what is your name?".writeLine()
val res = read()
return if (res.isBlank()) {
"empty name".writeLine()
program()
} else if (res == "me") {
"wrong name!".writeLine()
shift("wrong name")
} else println("Hello $res")
}
suspend fun main() {
with(Console.Default) {
effect<String, Unit> {
effect<EndOfLine, Unit> {
program()
}.fold({ println(it) }, { println(it) })
}.fold({ println(it) }, { println(it) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment