2010-04-11 144 views
90

在Scala中,您經常使用的迭代器做for迴路中增加的順序,如:斯卡拉向下或減少循環?

for(i <- 1 to 10){ code } 

你怎麼就這麼從10變爲1辦呢?我猜10 to 1給出了一個空的迭代器(就像平常的數學範圍一樣)?

我做了一個Scala腳本,它通過調用迭代器上的反向來解決它,但在我看來這不是很好,下面的路要走嗎?

def nBeers(n:Int) = n match { 

    case 0 => ("No more bottles of beer on the wall, no more bottles of beer." + 
       "\nGo to the store and buy some more, " + 
       "99 bottles of beer on the wall.\n") 

    case _ => (n + " bottles of beer on the wall, " + n + 
       " bottles of beer.\n" + 
       "Take one down and pass it around, " + 
       (if((n-1)==0) 
        "no more" 
       else 
        (n-1)) + 
        " bottles of beer on the wall.\n") 
} 

for(b <- (0 to 99).reverse) 
    println(nBeers(b)) 

回答

180
scala> 10 to 1 by -1 
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) 
+1

@Felix:不客氣。我也應該指出,直到你可以用'to'來代替右邊的終點。左手端點始終包含在內。 – 2010-04-13 14:26:47

+0

我已經知道until,until也是Integers上的一個函數,但是,「by」必須是範圍/迭代器上的函數,無論從「to」和「until」函數返回什麼。無論如何,謝謝:) – Felix 2010-04-15 12:59:58

+3

蘭德爾的回答是最好的,但我認爲'Range.inclusive(10,1,-1)'值得一提。 – 2013-07-15 01:35:39

32

從@Randall答案是很乖,但完成的緣故,我想添加一些變化:

scala> for (i <- (1 to 10).reverse) {code} //Will count in reverse. 

scala> for (i <- 10 to(1,-1)) {code} //Same as with "by", just uglier. 
+9

第一個+1,但第二個是邪惡的 - 比'by'更不可讀,國際海事組織在任何情況下都不應該使用 – 2012-04-13 20:14:23

+4

第二個是邪惡的,但是對可用的東西有直覺 – Zaheer 2014-08-19 00:05:30

6

帕斯卡爾已經編程,我覺得這個定義很好用:

implicit class RichInt(val value: Int) extends AnyVal { 
    def downto (n: Int) = value to n by -1 
    def downtil (n: Int) = value until n by -1 
} 

這樣使用:

for (i <- 10 downto 0) println(i) 
+0

感謝您的回答。我無法使用此解決方案。這裏是我的堆棧跟蹤:錯誤:(57,17)值類可能不是其他類的成員 隱式類RichInt(val值:Int)擴展AnyVal – robert 2015-12-22 20:40:13

+0

由於錯誤消息(不是堆棧跟蹤)建議,你不能在另一個類中定義值類。可以在它外面定義它,或者移除一個對象,或者刪除'extends AnyVal'部分(它只用於消除一些開銷)。 – 2016-01-05 14:40:16

3

斯卡拉提供了很多方法來向下循環工作。

第一解決方案:用 「到」 和 「通過」

//It will print 10 to 0. Here by -1 means it will decremented by -1.  
for(i <- 10 to 0 by -1){ 
    println(i) 
} 

第二解決方案:通過 「到」 和 「反向」

for(i <- (0 to 10).reverse){ 
    println(i) 
} 

第三解決方案: 「到」 僅

//Here (0,-1) means the loop will execute till value 0 and decremented by -1. 
for(i <- 10 to (0,-1)){ 
    println(i) 
} 
+2

所有這些選項已經被覆蓋(幾年前)。 – jwvh 2016-07-29 09:29:29