-
-
Save ianbattersby/5201036 to your computer and use it in GitHub Desktop.
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() | |
} | |
) | |
} | |
} |
Also, when (true) {...}
is not needed: use when {...}
You can say it divides 15
instead of it.divides(15)
"$i"
instead i.toString()
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.
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
).
If you want to go from 0 to 100? you can just say
0..100