0
(define x 2)

(let ((x 1) (y (+ x 1))) (+ x y))

you get 4;

(let* ((x 1) (y (+ x 1))) (+ x y))

you get 3.

I do not understand how the let thing works. Could someone please explain, i'm new to computer science thanks

Will Ness
  • 70,110
  • 9
  • 98
  • 181
HelpMeplox
  • 21
  • 1

1 Answers1

3
(let ((x 0) (z x))
  ...)

Is equivalent to:

((lambda (x z) ...) 0 x)

Perhaps in the anonymous procedure call you can see that when the arguments are evaluated the variable inside the body does not exist yet, but inside the body x is 0 and the previous x is shadowed in the whole body but accesible as z.

(let* ((x 0) (z x))
  ...)

Which is equivalent to:

(let ((x 0))
  (let ((z x))
    ...))

Looking at this you see right away that x gets set to 0 and shadows any other x at the time z gets bound.

Imagine you want to calculate the hypothenus og a triangle:

(let ((hypotenuse (sqrt (+ (square a) (square b)))))
  ...)

You want to split it up a little so you change it to a let* like this:

(let* ((sqa (square a))
       (sqb (square b))
       (hypotenuse (sqrt sqa sqb)))
  ...)

If you woudl have used let then sqa and sqb wuldn't be available! The rule of thumb is to use let and change it to a let* when you need to reference something bound in the same let. Be careful to not shadow variables you are using later.

Sylwester
  • 47,942
  • 4
  • 47
  • 79