Created
March 19, 2013 23:18
-
-
Save ianbattersby/5201036 to your computer and use it in GitHub Desktop.
Fizzbuzz in Kotlin
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
inline fun Int.divides(d: Int) : Boolean { return this % d == 0 } | |
fun main(args: Array<String>) : Unit { | |
var i = 0 | |
iterate { i++ } take 100 forEach { | |
println( | |
when (true) { | |
it.divides(15) -> "fizzbuzz" | |
it.divides(3) -> "fizz" | |
it.divides(5) -> "buzz" | |
else -> i.toString() | |
} | |
) | |
} | |
} |
I came up with a somewhat different approach since one expression of the problem I saw extended it to multiples of 7 with the string "bang" and that began to blow up with the approach above. I used a sequence with map functions as follows:
generateSequence(1 to "") { it.first+1 to "" }.map {
if(it.first.divides(3)) it.first to it.second+"fizz" else it
}.map {
if(it.first.divides(5)) it.first to it.second+"buzz" else it
}.map {
if(it.first.divides(7)) it.first to it.second+"bang" else it
} .map {
if (it.second.isEmpty()) it.first.toString() else it.second
}.take(110).forEach {
println (it)
}
I start with a Pair<Int, String> and generate a sequence and map over the sequence adding the appropriate strings (or not, as applicable). Then take 110 elements (to get at least one value with all three strings in it) and print each one.
Of course, the first three map
lambdas are very similar and can be refactored to a function...
BTW, this is valid for Kotlin 1.0.0+ (generateSequence
vs. iterate
or sequence
).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Haskell version here doesn't have println(), so for a fair comparison you could use the map() function instead of forEach(), as Neil does.