Last active
December 3, 2017 07:47
-
-
Save sys1yagi/526be942e522e92a959a849311f7f9dc to your computer and use it in GitHub Desktop.
Implement fizzbuzz with actor of kotlin coroutine.
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
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) |
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
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