簡體   English   中英

為什么此Scala行返回一個Unit?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM