ZetCode

Scheme variables and binding

last modified November 24, 2026 Guile 3.0

A Scheme variable is a name bound to a location that holds a value. Top-level names are created with define, local names with let and its relatives, and parameters when a procedure is called. set! changes the value stored in an existing binding. This article covers these forms and the scope rules that decide which binding a name refers to. The examples run with GNU Guile 3.0.7.

Assignment with set!

The basics article bound names with define. To change the value of a variable that already exists, Scheme uses set!. Its first operand is the name, which is not evaluated, and its second is the new value. The exclamation mark marks an operation that changes state.

assignment.scm
(define counter 0)

(define (increment!)
  (set! counter (+ counter 1)))

(display counter)
(newline)
(increment!)
(increment!)
(increment!)
(display counter)
(newline)
(set! counter (* counter 10))
(display counter)
(newline)

increment! reads counter, adds one, and stores the result back. After three calls the counter is 3, and the last set! multiplies it by 10. Scheme programs use assignment less often than programs in most other languages; many values are computed once and never changed. The name of a procedure that modifies a variable conventionally ends with ! as well.

$ guile assignment.scm
0
3
30

Assigning an undefined name

set! changes an existing binding; it does not create one. A typing mistake in the name therefore does not silently create a new variable, as it would in some scripting languages.

undefined.scm
(define total 10)

(set! total (+ total 5))
(display total)
(newline)
(set! totl 0)

The compiler warns that totl may be unbound. The program runs, prints 15, and stops at the set! with Unbound variable: totl. The backtrace is left out here.

$ guile undefined.scm
;;; undefined.scm:6:0: warning: possibly unbound variable `totl'
15
undefined.scm:6:0: Unbound variable: totl

Redefining a top-level name

At the top level of a program, define may be used again for a name that is already defined. The second definition then acts like an assignment and replaces the value. Guile accepts this but warns about it, because a second definition of the same name is often a mistake.

defining.scm
(define planet "Mars")
(define moons 2)

(display planet)
(display " has ")
(display moons)
(display " moons")
(newline)

(define planet "Jupiter")
(define moons 95)

(display planet)
(display " has ")
(display moons)
(display " moons")
(newline)

Both definitions take effect in order, so the first two lines print Mars and the last ones print Jupiter. The compiler reports that each second definition shadows the earlier one and gives the line and column of both. To change a value on purpose, set! states the intent and keeps the compiler quiet.

$ guile defining.scm
;;; defining.scm:10:0: warning: shadows previous definition of `planet' at defining.scm:1:0
;;; defining.scm:11:0: warning: shadows previous definition of `moons' at defining.scm:2:0
Mars has 2 moons
Jupiter has 95 moons

Local variables with let

let creates local variables that exist only inside its body. The first operand is a list of bindings, each a name and an expression in parentheses, and the rest is the body. The value of the last body expression is the value of the whole let.

local.scm
(define (rectangle-report width height)
  (let ((area (* width height))
        (perimeter (* 2 (+ width height))))
    (display "area: ")
    (display area)
    (display ", perimeter: ")
    (display perimeter)
    (newline)))

(rectangle-report 3 4)
(rectangle-report 10 2)

(display
 (let ((x 5)
       (y 7))
   (* x y)))
(newline)

Inside rectangle-report, area and perimeter are computed once and used in the body. They are not visible outside the let, so each call gets fresh variables. The second let stands at the top level and is used as an expression: its value, the product of x and y, is passed straight to display.

$ guile local.scm
area: 12, perimeter: 14
area: 20, perimeter: 24
35

let binds in parallel

All the initial values of a let are evaluated before any of the new variables exist. An expression in the binding list therefore cannot see the other variables of the same let; it sees the bindings outside.

parallel.scm
(define x 100)

(display
 (let ((x 1)
       (y x))
   (list x y)))
(newline)

(display x)
(newline)

The new x is 1, but the expression for y is evaluated before that binding exists, so it reads the top-level x, which is 100. list collects the two values into a list for printing. After the let, the name x again refers to the top-level variable, which was never changed.

$ guile parallel.scm
(1 100)
100

Sequential binding with let*

let* binds its variables one after another, so each expression can use the variables bound before it. It is the natural choice when a computation proceeds in steps.

sequential.scm
(define x 100)

(display
 (let* ((x 1)
        (y x))
   (list x y)))
(newline)

(define (circle radius)
  (let* ((pi 3.14159)
         (diameter (* 2 radius))
         (circumference (* pi diameter))
         (area (* pi radius radius)))
    (list diameter circumference area)))

(display (circle 10))
(newline)

With let*, y sees the new x, and both are 1. circle computes each value from the previous ones: the circumference uses pi and diameter, and the area uses pi and the parameter. Written with plain let, the references to pi and diameter would fail. The inexact results come from the decimal value of pi.

$ guile sequential.scm
(1 1)
(20 62.8318 314.159)

lambda

A procedure is created by a lambda expression, which lists the parameters and the body. A lambda expression produces an anonymous procedure; define can then give it a name. The procedure form of define used so far is a shorthand: (define (cube x) ...) means (define cube (lambda (x) ...)).

lambdas.scm
(define square
  (lambda (x) (* x x)))

(define (cube x)
  (* x x x))

(display (square 6))
(newline)
(display (cube 3))
(newline)
(display ((lambda (a b) (+ a b)) 4 5))
(newline)

(define area-of-square square)
(display (area-of-square 9))
(newline)

square is defined with an explicit lambda and cube with the shorthand; the two forms are equivalent. A lambda can also be called directly, without a name, by putting it in the operator position. Finally, area-of-square is bound to the same procedure as square, so both names call the same code. The procedures article returns to lambda with optional and rest arguments.

$ guile lambdas.scm
36
27
9
81

Local procedures and let

Because let evaluates all its expressions before binding the names, one local procedure cannot call another procedure from the same let. The next program tries it.

letfail.scm
(display
 (let ((double (lambda (x) (* 2 x)))
       (quadruple (lambda (x) (double (double x)))))
   (quadruple 5)))
(newline)

The lambda for quadruple is created where the local double is not yet visible, so its body refers to a top-level double, which does not exist. The compiler warns about it, and the call fails at run time.

$ guile letfail.scm
;;; letfail.scm:3:31: warning: possibly unbound variable `double'
letfail.scm:3:31: Unbound variable: double

letrec

letrec creates all its variables first and then evaluates the expressions inside their scope. The expressions are usually lambda expressions, and each procedure can refer to every name of the same letrec, including its own.

siblings.scm
(display
 (letrec ((double (lambda (x) (* 2 x)))
          (quadruple (lambda (x) (double (double x)))))
   (quadruple 5)))
(newline)

The program is the failing one with let replaced by letrec. Now the body of quadruple refers to the local double, and the result is 20. R7RS also has letrec*, which evaluates the expressions in order like let* does.

$ guile siblings.scm
20

A recursive local procedure

Since a letrec procedure can refer to its own name, it can call itself. The next program defines a local procedure that adds the numbers from 1 to n by calling itself with the next number and a running total.

recursive.scm
(define (sum-to n)
  (letrec ((loop (lambda (i acc)
                   (if (> i n)
                       acc
                       (loop (+ i 1) (+ acc i))))))
    (loop 1 0)))

(display (sum-to 10))
(newline)
(display (sum-to 100))
(newline)

loop receives the current number i and the sum so far in acc. When i passes n, it returns the sum; otherwise it calls itself with the next number and the updated sum. The local procedure sees n, the parameter of sum-to. The recursion and tail calls and iteration articles explain this style in detail.

$ guile recursive.scm
55
5050

Internal definitions

A define at the start of a procedure body creates a local variable or a local procedure rather than a top-level one. Internal definitions behave like letrec*: they are evaluated in order, and each can use the earlier ones. Many programmers prefer them to let for helpers.

internal.scm
(define (invoice-total price quantity)
  (define tax-rate 1/5)
  (define net (* price quantity))
  (define tax (* net tax-rate))
  (+ net tax))

(display (invoice-total 25 4))
(newline)
(display (invoice-total 12 3))
(newline)

(define (hypotenuse a b)
  (define (square x) (* x x))
  (sqrt (+ (square a) (square b))))

(display (hypotenuse 3 4))
(newline)
(display (hypotenuse 5 12))
(newline)

invoice-total defines a tax rate, a net amount, and the tax, each using the previous definitions. The tax rate is the exact fraction 1/5, so the second result is the exact value 216/5 rather than a rounded decimal. hypotenuse defines a local square procedure that is invisible outside it, and sqrt returns exact results 5 and 13 because the sums are perfect squares.

$ guile internal.scm
120
216/5
5
13

Lexical scope and shadowing

Scheme uses lexical scope: a name refers to the nearest binding that encloses it in the source code. An inner binding with the same name shadows the outer one within its region. A procedure sees the bindings that surround its definition, not those of the place where it is called.

scope.scm
(define name "global")

(define (show-name)
  (display name)
  (newline))

(define (shadow name)
  (display name)
  (newline)
  (show-name))

(shadow "parameter")

(let ((name "let"))
  (display name)
  (newline)
  (let ((name "inner let"))
    (display name)
    (newline))
  (display name)
  (newline)
  (show-name))

Inside shadow, the parameter name hides the top-level variable, so the first line is parameter. The call to show-name from there prints global: the body of show-name was written at the top level, where name means the top-level variable, and the caller's parameter does not matter. The nested let forms shadow each other in turn, and after the inner one ends, the outer let binding is visible again.

$ guile scope.scm
parameter
global
let
inner let
let
global

Source

Binding constructs — GNU Guile Reference Manual

R7RS: the Revised7 Report on Scheme

In this article we have changed variables with set!, redefined top-level names, created local variables with let and let*, written procedures with lambda, defined local and recursive procedures with letrec and internal definitions, and followed the rules of lexical scope. The numbers article continues with arithmetic on exact and inexact values.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.