In section 7.2, we mentioned the need to convert the while loop of update Var to a more functional style that uses only Val, and sometimes you can use recursion. The following example is a recursive function that approximates a value by constantly improving the guessing number:
def approximate (guess:double): Double =
if (Isgoodenough (guess)) guess
else approximate (improve (guess))
Such functions, with the appropriate isgoodenough and improve implementations, are often used in lookup problems. If you want the approximate function to execute faster, you may be tempted to write with a while loop to try to speed it up, such as:
def approximateloop (initialguess:double): Double = {
var guess =
initialguess
while (!isgoodenough (guess))
Guess = improve (guess)
Guess
}
Which of the two approximate versions is better? In terms of simplicity and avoidance of Var, the first, functional-style winner. But is the directive approach perhaps more efficient? In fact, if we measure the execution time, we will find that they are almost identical! This can be surprising, because recursive calls look more time-consuming than simply jumping from the end of the loop to the beginning.
However, in the example above approximate, the Scala compiler can apply an important optimization. Note that recursive invocation is the last thing the approximate function body performs. Like approximate, calling their own function in their last action is called tail recursion: tail recursive. The Scala compiler detects the tail recursion and updates the function parameter with the new value, and then replaces it with a jump that returns to the beginning of the function.
Morally you should not be ashamed of using recursive algorithms to solve your problems. Recursion is often more graceful and concise than a loop based approach. If the scenario is tail recursion, there is no run-time overhead.
Trace Tail recursive function
The tail recursive function will not create a new stack frame for each call; This may surprise programmers who have checked the program's stack trace and failed. For example, this function calls itself several times and throws an exception:
Def boom (x:int): Int =
if (x = = 0) throw new Exception ("boom!")
else Boom (x-1) + 1