Scheme's funky 'let' loop

In my previous post, I used this construct to loop for *max-iterations*:

(let loop ((i 0))
    (unless (= i *max-iterations*)
        (fac 30)
        (loop (+ i 1))))

This useful idiom is called a named let. The let special form is not intended for looping, but can be used for that purpose by calling the name (in this case, loop) recursively. Note that loop is just a name rather than a Scheme keyword or built-in function or form. We could give the loop any name.

I had actually forgotten about this form until I saw it again in a newsgroup post. By comparison, the "normal" let looks like this:

(let ((name1 value1)
      (name2 value2)
      ...etc...)
   ...body...)

The named let doesn't use as much magic as you might think, since it's basically a shorthand for a letrec with a lambda.

Leave a Comment