Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active December 3, 2017 07:47
Show Gist options
  • Save sys1yagi/526be942e522e92a959a849311f7f9dc to your computer and use it in GitHub Desktop.
Save sys1yagi/526be942e522e92a959a849311f7f9dc to your computer and use it in GitHub Desktop.
Implement fizzbuzz with actor of kotlin coroutine.
class Value(val value: Int, var output: String = "")
fun rule(seed: Int, print: String, next: SendChannel<Value>) = actor<Value> {
for (value in channel) {
next.send(value.apply {
if (value.value % seed == 0) {
this.output += print
}
})
}
}
fun printer() = actor<Value> {
for (value in channel) {
if (value.output.isNotEmpty()) {
println(value.output)
} else {
println(value.value)
}
}
}
fun fizz(next: SendChannel<Value>) = rule(3, "Fizz", next)
fun buzz(next: SendChannel<Value>) = rule(5, "Buzz", next)
fun main(args: Array<String>) = runBlocking<Unit> {
val fizzBuzz = fizz(buzz(printer()))
repeat(100) {
fizzBuzz.send(Value(it + 1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment