Mik*_*ike 7 functional-programming scala
这里有一些Scala代码可以将1到9之间的值相加,可以被3或5整除.为什么第5行返回Unit而不是布尔类型?
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)
}
}
Run Code Online (Sandbox Code Playgroud)
我们能不能过于惯用?我们可以!
Set(3,5).map(k => Set(0 until n by k:_*)).flatten.sum
Run Code Online (Sandbox Code Playgroud)
[编辑]
丹尼尔的建议看起来更好:
Set(3,5).flatMap(k => 0 until n by k).sum
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案:
scala> val answer = (1 until 10) filter( current => (current % 3 == 0) || (current % 5 == 0)) sum
answer: Int = 23
Run Code Online (Sandbox Code Playgroud)
注意过滤器而不是if.
另一个更加惯用的Scala:
( for( x <- 1 until 10 if x % 3 == 0 || x % 5 == 0 ) yield x ) sum
Run Code Online (Sandbox Code Playgroud)