Music 220b: Winter 2001
Fernando Lopez-Lezcano, instructor
Christopher Burns, teaching assistant
Tamara Smyth, teaching assistant
Week 2: variables
Lisp, like other programming languages, relies heavily upon the use of variables. Variables come in two types: global and local. An example of a global variable is CLM's *srate*: any CLM function might need to know what the current sampling rate is, and so the variable is available across the lisp environment. Local variables, by contrast, are only defined and usable within a limited scope. For instance, we might write two different instruments, each of which has a variable called pitch-envelope. If we make these variables local within the instruments, we can set each to a unique value without its influencing the other.
Global variables: setf
To create a global variable or to change its binding, we use (setf). This is equivalent to the Scheme (set!).
CM(16): (setf foo 1) 1 CM(17): (setf bar (+ 2 foo)) 3 CM(18): (setf foo (+ 2 bar)) 5 CM(19): foo 5 CM(20): bar 3
Local variables: let*
To create local variables, we use (let*). We usually prefer let* to plain let, although in many cases they will be identical. The difference is that (let*) creates its bindings sequentially, so that once we've defined a variable, we can use it in the definition of additional variables:
CM(22): (let* ((c 5) (d (* c 2))) (+ c d)) 15
The variables defined by let* only exist within the parentheses surrounding the let*:
CM(23): (let* ((a 1) (b 2)) (+ a b)) 3 CM(24): (+ a b) Error: Attempt to take the value of the unbound variable `A'.
However, this means we can temporarily reuse the names of global variables, without affecting those global variables:
CM(21): (let* ((foo 17) (bar 19)) (+ foo bar)) 36 CM(26): foo 5 CM(27): bar 3
Good programming style dictates that we use local variables whenever possible; this minimizes the possibility of conflicts with other programs (including our own).
Course resources main page
220b main page