Search code examples
loopsschemeletnamedchicken-scheme

Syntax of let in scheme


I can't understand this use of let in an example I found. I'm using chicken scheme.

(let loop ()
    (print "hello world")
    (loop)
)

It's a simple infinite loop, it recursively calls itself, what I can't understand is the syntax. I know that the first argument must be a list of pairs ((<var[1]> <value[1]>)...(<var[n]> <value[n])) and the other arguments are the body of the let. So, why does this snippet work?


Solution

  • That's a named let, which is shorthand for a helper procedure, typically used for looping using recursion, with parameters that advance as the recursion progresses (although in you code no parameters were used). For example, this procedure:

    (define (test)
      (let loop ((i 5))
        (cond ((<= i 0) 'ok)
              (else (print i)
                    (loop (- i 1))))))
    

    ... is equivalent to this one:

    (define (test)
      (define (loop i)
        (cond ((<= i 0) 'ok)
              (else (print i)
                    (loop (- i 1)))))
      (loop 5))
    

    Now you see that the snippet of code in the question is the same as writing this:

    (define (loop)
      (print "hello world")
      (loop))
    
    (loop)
    

    Also notice that the name "loop" is just a convention, you might as well name it "iter" or "helper" or any other thing you fancy, it doesn't really matter.