What is the difference between let, let*, and letrec?
Please give thorough explanations and examples.
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
.