Below is an example used to illustrate how to use immutable variables. (1) What function is this method performing and (2) which portion is considered the accumulator?
def fib(n: Int): Int = {
def fibIter(i: Int, a: Int, b: Int): Int =
if (i == n) a else fibIter(i+1, b, a+b)
fibIter(0, 0, 1)
}
As mentioned by @jwvh in his comment, this is a function for computing the nth term of the Fibonacci sequence.
This particular implementation is tail recursive and uses the inner function fibIter
as an "accumulator." Often in order to code a tail recursive implementation of a recursive function, it is useful to define an inner tail recursive function that accumulates the desired result. The outer function will the call this inner function with some default params. Sometimes this inner function is called "accumulate" or "go" or "loop", etc.
Here would be my preferred implementation of a Fibonacci similar to the above...
def fibonacci(n: Int): Int = {
@annotation.tailrec
def iterate(i: Int, a: Int, b: Int): Int =
if (i == n) a else iterate(i+1, b, a+b)
iterate(0, 0, 1)
}
...here I prefer to call the inner function iterate
because this is a more accurate description of what the function is doing (i.e., it isn't really accumulating anything).