Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decreasing for loop in Scala?

Tags:

scala

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

like image 955
rwb Avatar asked Apr 02 '12 13:04

rwb


1 Answers

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
like image 175
dacwe Avatar answered Sep 18 '22 03:09

dacwe