next up previous
Next: 5.3 Tail Recursion Up: 5 Iteration Previous: 5.1 Scheme Example

5.2 J Example

Next we consider an alternate solution to the problem from Section 2.3 of computing the product of the integers 1 to k which does not use the divide and conquer strategy.

The definition

factorial_iter =: monad define script
('n' ; 'acc' ; 'i') =. y.
if. i > n
  do. acc
  else. factorial_iter n , (i * acc) , i + 1
end.
)

computes the product of the integers 1 to 5 when applied to the argument 5 1 1.

A cover function for factorial_iter may be defined as

factorial1 =: monad define 'factorial_iter y. , 1 1'

so that factorial1 5 produces a result of 120.

The analysis of factorial_iter is similar to the analysis of sum-iter in Section 5.1. The continuation of the recursive call to factorial_iter in the definition of factorial_iter is

monad define 'y.'

Hence, no continuations need be saved and an optimizing compiler or interpreter will replace the recursion with iteration which directly computes the product of the integers 1 to k using a single call to factorial_iter.


next up previous
Next: 5.3 Tail Recursion Up: 5 Iteration Previous: 5.1 Scheme Example
2002-11-26