While doing exercise 1.12 from Structure and Interpretation of Computer Programs, I needed to learn an interesting technique for recursion. How does one write a nested loop in functional programming, i.e. recursively?
For example, consider this 2-dimensional loop:
How would this loop look in Scheme? Think of the problem in these steps:
- You will only write one function. (You don’t need to write a function for
every
for
loop.) - Every looping variable, along with any other state that changes along the course of the operation, must become a parameter to the function.
- Every
for
loop becomes anif
statement which helps the function determine where it is in the process.
This is the final product in Scheme:
The output of both programs should be identical.