Java Reference
In-Depth Information
}
The function factorialHelper is tail recursive because the recursive call is the last thing that
happens in the function. By contrast in our previous definition of factorial-Recursive, the last
thing was a multiplication of n and the result of a recursive call.
This form of recursion is useful because instead of storing each intermediate result of the
recursion onto different stack frames, the compiler can decide to reuse a single stack frame.
Indeed, in the definition of factorialHelper, the intermediate results (the partial results of the
factorial) are passed directly as arguments to the function. There's no need to keep track of the
intermediate result of each recursive call on a separate stack frameā€”it's accessible directly
through the argument of the function.
Figures 13.5 and 13.6 illustrate the difference between the recursive and tail-recursive
definitions of factorial.
Figure 13.5. Recursive definition of factorial, which requires several
stack frames
 
Search WWH ::




Custom Search