首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala向下还是递减for循环?

Scala向下还是递减for循环?
EN

Stack Overflow用户
提问于 2010-04-11 23:22:08
回答 7查看 53.4K关注 0票数 124

在Scala中,您经常使用迭代器以递增的顺序执行for循环,如下所示:

代码语言:javascript
复制
for(i <- 1 to 10){ code }

你怎么做才能从10到1呢?我猜10 to 1给了一个空的迭代器(就像通常的范围数学一样)?

我做了一个Scala脚本,它通过在迭代器上调用reverse来解决这个问题,但在我看来,这并不好,下面的方法是可行的吗?

代码语言:javascript
复制
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))
EN

Stack Overflow用户

发布于 2014-05-14 05:54:37

在用Pascal编写程序后,我发现这个定义很好用:

代码语言:javascript
复制
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
}

这样使用:

代码语言:javascript
复制
for (i <- 10 downto 0) println(i)
票数 6
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2617513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档