Below recursive method sums the integer values between a range
def sumInts(a: Int, b: Int): Int = {
if(a > b) 0
else {
println(a +"," + b)
a + sumInts(a + 1 , b)
}
}
So sumInts(2 , 5) returns 14
I’m confused about how the recursive call to sumInts sums the integer range. Can explain textually how this method works ?
How does sumInts return the incremented value ?? Perhaps I am missing something fundamental to recursion here
It calculates the sum of values in the range [a, b] by first calculating the sum of the range [a+1, b] (by recursively calling
sumInts(a + 1 , b)) then addingato it.[Update] In Scala, the
returnstatement is optional; functions return the value of the last expression evaluated. Thus the above function body is equivalent to[/Update]
Which for the range [2, 5] it would do the following (I removed the
printlncall for the sake of simplicity, and added brackets to mark recursive calls):if(2 > 5) 0 else 2 + sumInts(2 + 1, 5)which, the condition beingfalse, evaluates to2 + sumInts(3, 5)2 + (if(3 > 5) 0 else 3 + sumInts(3 + 1, 5))which evaluates to2 + (3 + sumInts(4, 5))2 + (3 + (if(4 > 5) 0 else 4 + sumInts(4 + 1, 5)))which evaluates to2 + (3 + (4 + sumInts(5, 5)))2 + (3 + (4 + (if(5 > 5) 0 else 5 + sumInts(5 + 1, 5))))which evaluates to2 + (3 + (4 + (5 + sumInts(6, 5))))2 + (3 + (4 + (5 + (if(6 > 5) 0 else 6 + sumInts(6 + 1, 5)))))which, the condition beingtrue, evaluates to2 + (3 + (4 + (5 + (0))))