3.1.3 Defining and Setting Variables

To define a new variable, you use Scheme’s define syntax like this:

(define variable-name value)

This makes a new variable called variable-name and stores value in it as the variable’s initial value. For example:

;; Make a variable `x' with initial numeric value 1.
(define x 1)

;; Make a variable `organization' with an initial string value.
(define organization "Free Software Foundation")

(In Scheme, a semicolon marks the beginning of a comment that continues until the end of the line. So the lines beginning ;; are comments.)

Changing the value of an already existing variable is very similar, except that define is replaced by the Scheme syntax set!, like this:

(set! variable-name new-value)

Remember that variables do not have fixed types, so new-value may have a completely different type from whatever was previously stored in the location named by variable-name. Both of the following examples are therefore correct.

;; Change the value of `x' to 5.
(set! x 5)

;; Change the value of `organization' to the FSF's street number.
(set! organization 545)

In these examples, value and new-value are literal numeric or string values. In general, however, value and new-value can be any Scheme expression. Even though we have not yet covered the forms that Scheme expressions can take (see Expressions and Evaluation), you can probably guess what the following set! example does…

(set! x (+ x 1))

(Note: this is not a complete description of define and set!, because we need to introduce some other aspects of Scheme before the missing pieces can be filled in. If, however, you are already familiar with the structure of Scheme, you may like to read about those missing pieces immediately by jumping ahead to the following references.