减少 Scala 中的 for 循环? [英] Decreasing for loop in Scala?

查看:65
本文介绍了减少 Scala 中的 for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一天,也是第一次尝试使用 Scala - 所以放轻松!我正在尝试重写一些旧的 Java 代码,它只是一个函数,它接受两个数字并打印出从 x 到 y 的数字.例如,我有增量函数:

 def increment(start: Int, finish: Int) = {for (i <- 从开始到结束) {println("当前值(从"+start+"增加到"+finish+")是"+i)}}

但是,我正在努力编写一个从头到尾递减的相应递减函数?我已经阅读了 Scala 向下或减少 for 循环? 但我仍然不确定>

谢谢

解决方案

scala>def decrement(start: Int, finish: Int) = {|for (i <- 开始到结束 -1)|println("当前值(从+start+"减少到+finish+")为+i);|}递减:(开始:整数,结束:整数)单位标度>递减(10, 1)当前值(从 10 减少到 1)为 10当前值(从 10 减少到 1)为 9当前值(从 10 减少到 1)为 8当前值(从 10 减少到 1)为 7当前值(从 10 减少到 1)是 6当前值(从 10 减少到 1)为 5当前值(从 10 减少到 1)为 4当前值(从 10 减少到 1)为 3当前值(从 10 减少到 1)为 2当前值(从 10 减少到 1)为 1

First day and first attempt at using Scala - so go easy on me! I'm trying to rewrite some old Java code I have which is simply a function which takes two numbers and prints out the numbers from x to y. For example, i have the increment function:

    def increment(start: Int, finish: Int) = {
      for (i <- start to finish) {
         println("Current value (increasing from "+start+" to "+finish+") is "+i)
      }
    }

However, im struggling writting a corresponding decrement function which will decrease from start to finish? I have read Scala downwards or decreasing for loop? but am still unsure

Thank you

解决方案

scala>def decrement(start: Int, finish: Int) = {
    |  for (i <- start to finish by -1)
    |   println("Current value (decreasing from "+start+" to "+finish+") is "+i);
    | }
decrement: (start: Int,finish: Int)Unit

scala> decrement(10, 1)
Current value (decreasing from 10 to 1) is 10
Current value (decreasing from 10 to 1) is 9
Current value (decreasing from 10 to 1) is 8
Current value (decreasing from 10 to 1) is 7
Current value (decreasing from 10 to 1) is 6
Current value (decreasing from 10 to 1) is 5
Current value (decreasing from 10 to 1) is 4
Current value (decreasing from 10 to 1) is 3
Current value (decreasing from 10 to 1) is 2
Current value (decreasing from 10 to 1) is 1

这篇关于减少 Scala 中的 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆