[英]Why does this Scala line return a Unit?
这是一些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)
}
}
if表达式具有Unit类型,因为没有else子句。 因此,有时它什么都不返回(单位),因此整个表达式的类型为单位。
(我假设您是想问为什么它不返回Int而不是布尔值)
我们都不能太地道? 我们可以!
Set(3,5).map(k => Set(0 until n by k:_*)).flatten.sum
[编辑]
丹尼尔的建议看起来更好:
Set(3,5).flatMap(k => 0 until n by k).sum
这是我的解决方案:
scala> val answer = (1 until 10) filter( current => (current % 3 == 0) || (current % 5 == 0)) sum
answer: Int = 23
注意过滤器而不是if。
更加惯用的Scala中的另一个:
( for( x <- 1 until 10 if x % 3 == 0 || x % 5 == 0 ) yield x ) sum
与您所做的最接近的工作代码是:
object Euler {
def main(args : Array[String]) {
val answer = (1 until 10).foldLeft(0) ((result, current) =>
if ((current % 3 == 0) || (current % 5 == 0))
result + current
else
result
)
println(answer)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.