We've seen variables used, in expressions such as (- (* z 2)
1)
, and now that we have established the idea of special forms,
we can look at how variables are created.
The main way to create variables is a special form called
let
. The first sub-expression of let
is a
list of variables and their values, and the remaining sub-expressions
are any expressions, which are evaluated in order, the result of the
last one becoming the result of the whole let
expression.
(This is called an implicit progn, and is quite common.) While
those sub-expressions are being evaluated, the variables given at the
top of the let
are bound to the values given there. When
the let
finished, the variables disappear. So, for
example, you might read aloud
(let ((a 1) (b 2)) (+ a b))as let a be 1 and b be 2 in a plus b
It's also possible to change the value of a variable once it has been established, but there is a style of programming, called functional programming, in which a variable keeps the same value for its whole existence. Many experts consider this a good way to program, for reasons concerned with the mathematical logic underlying programming languages. We'll leave use of variables the other style of programming (generally called imperative programming or procedural programming) for another article.
However, note that if you bind the same variable (by the way,
binding is the technical term to establishing a variable and giving
it a value) in a let
that is inside another
let
, the inner binding takes precedence in the inner
let
, and the outer one reappears when you get back to the
outer let
. In fact, what is happening here is that the
outer one is irrelevant to the inner one; the inner one just makes its
binding as usual. The reason for this will appear much later in these
notes.
John C. G. Sturdy | Last modified: Sun Oct 28 22:44:22 GMT 2007 |