Try Firefox!

SI413 Scheme Lab 7: Breaking the functional paradigm further ... loops!

Loops in scheme: do
To loop in scheme you use the do function. It takes a bit of getting used to. Essentially it looks like this
(do ( (var1 init1 [optional update]) (var2 init2 [optional update]) ...)     ( (termination condition) (return expression) )
    (loop-body expression 1)
    (loop-body expression 2)
     ....
)
	
Probably best to see some examples. Note: do uses a "termination condition" not a "continuation condition" like C++/Java's while. So, when the condition is true you exit the loop, and the return expression is evaluated to get the value of the entire do expression.

create list (10 ... 1) - no "update" used create list (1 ... 10) - no "update" used
(do ((L '()) (i 0)) ((= i 10) L) 
  (set! i (+ i 1)) 
  (set! L (cons i L)))

(do ((L '()) (i 10)) ((= i 0) L) 
  (set! L (cons i L))
  (set! i (- i 1)))

In the previous example, loop variables were created in this list of "name/initial-value" pairs. You can add a third part, which is an "update-expression" that, after every loop iteration and before the termination condition test, is used to get a new value for the variable. The only subtlety with this is that any appearance of any loop variable in an undate-expression is the value of that variable before the current round of updating.

create list (10 ... 1) - using "update" to increment i create list (1 ... 10) - using "update" for both i and L
(do ((i 0 (+ i 1)) (L '())) ((= i 10) L) (set! L (cons (+ i 1) L)))
(do ((i 10 (- i 1)) (L '() (cons i L))) ((= i 0) L) )

The subtlety I mentioned before becomes clearer when we modify the loop that creates the list (10 ... 1) to use update expressions for both i and L:

(do ((i 0 (+ i 1)) (L '() (cons (+ i 1) L))) ((= i 10) L))
Notice that we cons (+ i 1) onto L, because the "i" in the update expression is the "old" value of i, not the "new" i.

Excercises
Using "do", do the following
  1. Write an expression that returns the sum of the first hundred integers
  2. Define a function (sum i j) that returns the sum of the integers in the range i ... j
  3. Define a function (sum V i j) that returns the sum of the values in vector V fromindex i to index j, i.e. V[i] + V[i+1] + ... + V[j]
  4. Define a function (sum L) that takes a list L and returns the sum of its elements


Christopher W Brown
Last modified: Wed Aug 27 09:02:20 EDT 2008