Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Syntax and Evaluation

Defining Names with define and let

Bind names to values with define, let, let* and letrec in Racket and Scheme. Learn lexical scope, shadowing, internal definitions and when to use set!.

A program needs names: a name for a value, a name for a function, a name for an intermediate result. Racket gives you two main tools. define creates a name for a whole module or function body, and the let family creates names that exist only inside one expression. Understanding which names are visible where, called scope, is the key to reading any Lisp program.

All examples run on the course's stand-in interpreter, which implements these forms with the same scoping rules as Racket.

define

define binds a name to a value:

RACKET
(define pi-ish 3.14159)
(define greeting "hello")
(define radius 5)
(* pi-ish radius radius)   ; 78.53975

To define a function, put the name and parameters in parentheses. These two definitions are equivalent:

RACKET
(define (square x) (* x x))
(define square (lambda (x) (* x x)))

The first is shorthand for the second: a function is a value, and define just gives it a name.

Define values and functions

The last line shows that double is a value: a procedure object.

let: local names

let introduces names that exist only inside its body:

RACKET
(let ([x 3]
      [y 4])
  (+ (* x x) (* y y)))   ; 25

The structure is (let (binding ...) body ...), where each binding is [name value]. After the let ends, x and y are gone.

All the values in a let are computed before any name is bound, so the bindings cannot see each other:

RACKET
(define x 1)
(let ([x 10]
      [y x])   ; this x is the OUTER x, so y is 1
  (list x y))  ; '(10 1)
let and its bindings

After the let, x is still 1: the inner binding was shadowing the outer one inside the body only.

let*: each binding sees the earlier ones

Use let* when a binding needs a previous one:

RACKET
(let* ([a 2]
       [b (* a 10)]    ; can use a
       [c (+ a b)])    ; can use a and b
  (list a b c))        ; '(2 20 22)

let* is the same as nested let forms, one inside the next.

letrec and named let

A let binding cannot refer to itself, which a recursive function needs. letrec binds names so they can see each other and themselves:

RACKET
(letrec ([even? (lambda (n) (if (= n 0) #t (odd? (- n 1))))]
         [odd?  (lambda (n) (if (= n 0) #f (even? (- n 1))))])
  (even? 10))   ; #t

A named let combines definition and first call for loops; you will use it constantly:

RACKET
(let loop ([i 0] [acc 0])
  (if (> i 4)
      acc
      (loop (+ i 1) (+ acc i))))   ; 10

loop is a function bound just inside the let; the initial values start the first call.

let*, letrec and named let

Lexical scope

Racket and Scheme use lexical scope: a name refers to the nearest enclosing binding in the text of the program, not to whatever is running at the moment. You can read the structure straight off the page:

RACKET
(define x "outer")
(define (show) x)          ; refers to the x in effect where show is written

(let ([x "inner"])
  (show))                  ; still "outer": show looks at its own surroundings
Lexical scope in action

x inside the let is "inner", but show still sees the outer x. This is the rule that makes closures, covered in a later chapter, work.

Internal definitions

Inside a function body (and many other bodies) you can use define to name helper values and functions. They are visible to everything after them in the same body:

RACKET
(define (hypotenuse a b)
  (define a2 (* a a))
  (define b2 (* b b))
  (sqrt (+ a2 b2)))
(hypotenuse 3 4)   ; 5

This style reads like a sequence of steps and is common in Racket. Do not use define where an expression is expected, such as inside an if branch.

set!: changing a binding

(set! name value) changes an existing binding:

RACKET
(define counter 0)
(set! counter (+ counter 1))
counter   ; 1

Lisp programmers use set! sparingly. The ! suffix is a convention for functions or forms that mutate. Prefer producing new values with recursion and let to updating variables. When you do need state, keep it small and local; later you will see closures used to encapsulate it.

A counter with set!

Common mistakes

  • Using a name before it is defined at module level gives undefined; cannot reference an identifier before its definition.
  • Forgetting that let bindings are parallel. Use let* when bindings depend on each other.
  • Extra parentheses around a binding: (let (x 3) ...) is wrong; each binding needs its own brackets, ([x 3]).
  • Using define for a quick local name inside an expression. Use let there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (let ([x 1] [y x]) y) refer to if x is already defined as 5 outside?

    let bindings are evaluated in parallel in the outer scope, so the x in [y x] is the outer x, which is 5.
  2. 2. Which form lets each binding use the previous ones?

    let* evaluates bindings in order, so later ones can see earlier ones.
  3. 3. What does lexical scope mean?

    Lexical scope resolves a name from the program's structure, not from the call stack.
  4. 4. What is (define (f x) x) shorthand for?

    A function is a value; the parenthesized define is just a convenient way to name a lambda.

Summary

  • define binds a name (or a function) in the current scope; let binds names for one body.
  • let bindings are parallel, let* is sequential, letrec allows self- and mutual references, and named let is a loop form.
  • Scope is lexical: look at the surrounding text to find a name's binding.
  • Internal defines inside a body are tidy for helpers.
  • set! mutates; use it sparingly.

Next: Strings, Characters and Symbols