# 9.1 Assignment

The set! (pronounced "set-bang!") special form associates a new value with an already defined name. The exclamation point at the end of set! follows a naming convention to indicate that an operation may mutate state. A set expression is also known as an assignment. It assigns a value to a variable.

The grammar rule for assignment is:

The evaluation rule for an assignment is:
Evaluation Rule 7: Assignment. To evaluate an assignment, evaluate the expression, and replace the value associated with the name with the value of the expression. An assignment has no value.

Assignments do not produce output values, but are used for their side effects. They change the value of some state (namely, the value associated with the name in the set expression), but do not produce an output.

Here is an example use of set!:

> (define num 200)
> num
200
> (set! num 150)
> (set! num 1120)
> num
1120

Begin expression. Since assignments do not evaluate to a value, they are often used inside a begin expression. A begin expression is a special form that evaluates a sequence of expressions in order and evaluates to the value of the last expression.

The grammar rule for the begin expression is:

The evaluation rule is: Evaluation Rule 8: Begin. To evaluate a begin expression,

$$(\text{begin} \text{ Expression}_1 \text{ Expression}_2 \ldots \text{ Expression}_k)$$

evaluate each subexpression in order from left to right. The value of the begin expression is the value of the last subexpression, $\text{Expression}_k$.

The values of all the subexpressions except the last one are ignored; these subexpressions are only evaluated for their side effects.

The begin expression must be a special form. It is not possible to define a procedure that behaves identically to a begin expression since the application rule does not specify the order in which the operand subexpressions are evaluated.

The definition syntax for procedures includes a hidden begin expression.

(define (Name Parameters) MoreExpressions Expression)

is an abbreviation for:

(define Name
(lambda (Parameters) (begin MoreExpressions Expression)))

The let expression introduced in Section 8.1.1 also includes a hidden begin expression.

$$(\text{let } ((\text{Name}_1 \text{ Expression}_1) (\text{ Name}_2 \text{ Expression}_2) \\ \cdots (\text{ Name}_k \text{ Expression}_k)) \\ \text{MoreExpressions} \text{ Expression})$$

is equivalent to the application expression:

$$((\text{lambda} (\text{ Name}_1 \text{ Name}_2 \ldots \text{ Name}_2) \\ (\text{begin} \text{ MoreExpressions} \text{ Expression})) \\ \text{ Expression}_1 \text{ Expression}_2 \ldots \text{ Expression}_k)$$