Previous chapter: Introduction to Functions and Classes

Dylan manual: Assignment

7. Assignment

The Dylan special form set! is used to set variables to new values. It can also be used as alternate syntax for calling setter functions and macros.

set![return to first citation]   place new-value   ==>  new-value	[Special Form]
set! stores new-value in place. Subsequent evaluations of place will yield new-value. set! returns new-value.

place can be a variable name or it can be a list whose first element is a symbol. If place does not have one of these formats, an error is signaled at compile-time.

If place is a variable name, then new-value is stored in the corresponding variable (which may be a lexical or module variable). An error is signaled if there is no lexical or module variable corresponding to the place at the time set! is executed.

(The following example uses a function %set-element. The function does not actually exist in Dylan. It is meant to indicate a primitive, implementation-dependent operation for setting an element of a collection.)

? (define foo 10)
? foo             ;this is a variable
10                ;this is the variables contents
? (set! foo (+ 10 10))
? foo
? (setter element)                   ;this is a variable
{generic function (setter element)}  ;the variables contents
? (set! (setter element) %set-element)
{primitive function %set-element}
? (id? (setter element) %set-element)
If place is not a variable name, then it should have the syntax of a call to a function. This is called the extended form of set!. In this case, the function call indicates an accessible location. The call to set! should change what future accesses of the location will return.
? (define foo (vector 'a 'b 'c 'd))
? foo
#(a b c d)
? (element foo 2)
? (set! (element foo 2) 'sea)
? (element foo 2)
? foo
#(a b sea d)
In the general case,

(set! (symbol arg1...argn) new-value)
means roughly

((setter symbol) arg1...argn new-value)
(The meaning is actually somewhat more complicated than this, because set! guarantees that the new-value is returned, regardless of what is returned by the setter function.)

In the example above

(set! (element foo 2) 'sea)
is equivalent to

((setter element) foo 2 'sea)

Next chapter: Conditionals, Flow of Control, and Evaluation