Prev Up Next

A recursive procedure defined using letrec can describe loops. Let's say we want to display a countdown from 10:

(letrec ((countdown (lambda (i)
                      (if (= i 0) 'liftoff
                          (begin
                            (display i)
                            (newline)
                            (countdown (- i 1)))))))
  (countdown 10))

This outputs on the console the numbers 10 down to 1, and returns the result liftoff.

Scheme allows a variant of let called named let to write this kind of loop more compactly:

(let countdown ((i 10))
  (if (= i 0) 'liftoff
      (begin
        (display i)
        (newline)
        (countdown (- i 1)))))

Note the presence of a variable identifying the loop immediately after the let. This program is equivalent to the one written with letrec. You may consider the named let to be a macro (chap 8) expanding to the letrec form.

Prev Up Next

Log in or registerto write something here or to contact authors.