Scheme: When to use let, let*, and letrec?

14,106

Your best bet is to read the official R5RS descriptions of let, let*, and letrec.

In short, however:

(let ((x 2))
 (let ((x 3) (y x))
  y) => 2

(let ((x 2))
 (let* ((x 3) (y x))
  y) => 3

So the difference between let and let* is let will evaluate all the bindings with respect to the level above (so it doesn't matter what order they're listed in) while let* does it sequentially. (let* ((x a) (b y))) is equivalent to (let ((x a)) (let ((b y))).

letrec, on the other hand, allows you to bind recursive values. So you might write a recursive function that you only want to be within the function scope and bind it to a name using letrec.

Share:
14,106
Sol Bethany Reaves
Author by

Sol Bethany Reaves

Updated on July 18, 2022

Comments

  • Sol Bethany Reaves
    Sol Bethany Reaves almost 2 years

    What is the difference between let, let*, and letrec?

    Please give thorough explanations and examples.