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, Ada, or Java, 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 correctly deal with these questions, you need the concept of a continuation.


Exercise 2

Using a macro, we can extend Scheme to include a while expression, which expands into one using recursion as shown in the answer to the previous question.

(extend-syntax (while do)
  [(while C do S1 ...) 
   (letrec ([loop (lambda () (if C (begin S1 ... (loop))))]) (loop))])

Try (while (< x 10) do (printf "~s~n" x) (set! x (1+ x))) to see how it works.

Using this while construct and set!, write a program fact-loop to compute factorial.




rhyspj@gwu.edu