Most structured programming languages support a rich set of primitive control mechanisms. If you have programmed in C, Pascal, or Basic, you are familiar with various looping constructs (such as for, while, repeat, etc.) In fact, most programs in those languages use loops exclusively for performing repetitive tasks. Such a pattern of computation is called iteration because with each pass of the loop the program constructs a little bit more of the solution.
In Scheme, loops are often replaced by recursion. Even though these other languages also support recursion, you seldom see Scheme-style programs written in any of them. Why is this? Is there a substantial difference between recursion and iteration?
Let us try to construct a Scheme expression that acts like a while loop. A C-language while loop such as
while (C) { }
is equivalent to
Loop: if (C) { goto Loop}
Scheme, however, has no goto construct; yet there is a Scheme expression that does the same thing.
To deal with these questions in a precise way, you need the concept of a continuation.
Exercise 2
Using a syntactic extension, we can extend Scheme to include a while expression, which expands into one using recursion as shown in the
answer to the previous question.
Copy the following into Dr. Scheme:
(define-syntax while (syntax-rules (do) [(_ c do s1 ...) (let loop () (if c (begin s1 ... (loop))))]))
Now execute
to see how it works.(let ([x 0]) (while (< x 10) do (printf "~s~n" x) (set! x (add1 x))))
Using this while construct and set!, write a program fact-loop to compute factorial. Include the definition of while in your file.