local
's little cousin let
let
as an alternative
to local
.
If you only learn one or the other, local
is the one
to learn: it is more powerful.
(You cannot use mere let
for recursion, for instance;
nor can you use define-structure
inside let
.)
However, feel free to use let
if you like.
Be aware that the scoping rules are a little bit different for let
:
all the right-hand-sides are scoped as if they were outside
the let
.
(Recall in lecture, how let
is actually just
converted into a single lambda
expression.)
N.B. let
does not work in Donkey, only in Dr. Scheme.
The answer is let
, a new Scheme statement (covered
in Chapter 5 (postscript)).
The let
statement allows you to
create new, temporary placeholders, and give them a value.
The value of those new placeholders can then be used repeatedly.
Here's a simple example:
(let ([G 6.670e-11] ;; gravitation constant, in N m^2/kg^2 [M1 1.989e30] ;; mass of sun in kg [M2 5.965e24] ;; mass of earth in kg [r 1.496e10]) ;; mean earth-sun dist in m (/ (* G M1 M2 ) (* r r))) ;; gravitational force earth/sun, in newtonsThis shows one simple use of
let
: to make a calculation clearer
by name sub-computations. The placeholders M1
,
etc, have their values only inside the resultExp
.
For instance, try evaluating the above expression directly in
Dr. Scheme. After that, evaluate M1
, and
you should get the ol' "reference to unbound identifier: M1" error.
In general, the syntax of the let
statement is:
(let ([ph1 exp1] [ph2 exp2] ... [phn expn]) resultExp)where:
ph1
through phn
are place-holders
(variable names, if you prefer), and
exp1
through expn
are expressions,
whose value is associated with the placeholders.
What is the value returned by the entire let
statement?
It's the value of the expression resultExp
,
which may contain references to the placeholders ph1
, etc.
In writing your own let
s, notice how one set of parentheses
is around each placeholder/expression pair, and another set of
parentheses is around the list of these pairs. (I use square-parentheses
to help distinguish them, but square and round parentheses are equivalent
to Dr. Scheme.)
A difference from local
:
the expression exp2
can not use the placeholder ph1
!
More precisely, if exp2
mentions ph1
,
then it will take the binding of the placeholder ph1
from before the let
.
Of course,
resultExp
can itself be a let
statement
(evil grin).
If you like this idea, you might want to ask a labbie about
let*
, which is equivalent to nested-let
s.