Created
May 23, 2022 15:50
-
-
Save nomisRev/13eb7e68a943c3dde210ad7d075a2611 to your computer and use it in GitHub Desktop.
Console Effect handler
This file contains 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
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