Java Reference
In-Depth Information
We now have the following situation. Each tail-recursive call is followed by
a return statement. The final step of the transformation is as follows:
Step 3. Replace each tail-recursive call and following return
statement by code that assigns the arguments to the parameters
and then terminates the repetend using a continue statement.
In the case of setToZero , there is one tail-recursive call. Parameters b and
k need not be assigned since they are the same as the arguments. Parameter h is
assigned the value of the second argument, h+1 . The result of this transforma-
tion is shown below.
Each time you perform this transformation on a procedure, use the same
label for the additional loop and the same comment at the end of the loop. Also,
include the statement-comment for each recursive call, as done for setToZero
above. Finally, include the continue statement even if it is the last statement in
the repetend. Using these conventions will help you and others realize that this
transformation was applied to the procedure.
/** Set elements of b[h..k] to 0 */
public static void setToZero( int [] b, int k, int n) {
tailRecursionLoop: while ( true ) {
if (h > k)
{ return k; }
b[h]= 0;
// setToZero(b, h + 1, k);
h= h + 1;
continue tailRecursionLoop;
} // end tailRecursionLoop
}
15.3.4
Removing tail-recursion: functions
Removing tail-recursive function calls is similar:
Step 1. Enclose the function body in a labeled while loop with
loop condition true .
Step 2. Replace each tail-recursive return statement by code that
assigns the arguments to the parameters and then terminates exe-
cution of the repetend using a continue statement.
We illustrate the removal of tail-recursive function calls using this function:
 
Search WWH ::




Custom Search