Control Structures in Scheme

Chapter: Control Structures in Scheme

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?

Q. 2
Is there a uniform relationship 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) { S1; S2;... }

is equivalent to

Loop: if (C) { S1; S2;... goto Loop}

Scheme, however, has no goto construct; yet there is a Scheme expression that does the same thing.

Q. 3
Can you write a Scheme expression that behaves like a while loop?


Q. 4
Is this Scheme expression technically equivalent to the C while-loop?


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

(let ([x 0])
     (while (< x 10) do (printf "~s~n" x) (set! x (add1 x))))
to see how it works.

Using this while construct and set!, write a program fact-loop to compute factorial. Include the definition of while in your file.





rms@cs.oberlin.edu