Here's a bit of Scala code to sum the values from 1 to 9 which are divisible by 3 or 5. Why does line 5 return a Unit and not a Boolean type?
object Sample {
def main(args : Array[String]) {
val answer = (1 until 10).foldLeft(0) ((result, current) => {
if ((current % 3 == 0) || (current % 5 == 0)) {
result + current
}
})
println(answer)
}
}
The if expression has a type of Unit because there is no else clause. Thus sometimes it returns nothing (Unit) so the entire expression has type Unit.
(I assume you meant to ask why it didn't return Int, not Boolean)
Can we ever be too idiomatic? YES WE CAN!
Set(3,5).map(k => Set(0 until n by k:_*)).flatten.sum
[Edit]
Daniel's suggestion looks better:
Set(3,5).flatMap(k => 0 until n by k).sum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With