Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Higher-order Functions

Lambda and Closures

Learn anonymous functions with lambda, functions as values, and closures that remember their surroundings. Build counters, adders and private state step by step.

In Racket and Scheme a function is a value, just like a number or a string. You can store one in a variable, put it in a list, pass it to another function and return it from a function. Functions that take or return other functions are called higher-order functions, and they are the heart of this chapter. We start with the tool that creates function values, lambda, and the idea that makes them powerful: the closure.

Run examples use the stand-in interpreter, which implements closures with real lexical environments.

lambda: an unnamed function

(lambda (params ...) body ...) creates a function without naming it:

RACKET
(lambda (x) (* x x))          ; a function value
((lambda (x) (* x x)) 5)      ; call it right away: 25
(define square (lambda (x) (* x x)))
(square 6)                    ; 36

You already know that (define (square x) ...) is shorthand for this. Anonymous functions shine when you need a small function once, usually as an argument:

RACKET
(map (lambda (x) (+ x 1)) '(1 2 3))   ; '(2 3 4)

In DrRacket you can type ฮป instead of lambda; the two are identical.

Lambda values

map with two lists takes a two-argument function and walks both lists together.

Functions as values

Because functions are values, you can put them in data structures and choose between them at run time:

RACKET
(define operations (list + - * max))
(map (lambda (f) (f 12 4)) operations)   ; '(16 8 48 12)

You can pass a function to a function:

RACKET
(define (apply-twice f x) (f (f x)))
(apply-twice add1 5)            ; 7
(apply-twice (lambda (s) (string-append s "!")) "hey")   ; "hey!!"
Passing functions around

Returning functions

A function can build and return another function:

RACKET
(define (make-adder n)
  (lambda (x) (+ x n)))

(define add5 (make-adder 5))
(define add10 (make-adder 10))
(add5 3)     ; 8
(add10 3)    ; 13

Look closely. make-adder has returned, so its parameter n should be gone, yet add5 still uses 5. This is a closure: a function bundled with the variables from the place where it was created.

flowchart LR
    A["make-adder called with n = 5"] --> B["creates lambda (x) (+ x n)"]
    B --> C["closure: code + environment with n = 5"]
    C --> D["add5 holds the closure"]

The closure keeps its own copy of the surrounding environment.

Each call to make-adder creates a separate environment, so add5 and add10 do not interfere.

make-adder closures

Closures with private state

A closure can keep a variable that only it can touch. Combined with set!, that gives you encapsulated state without classes:

RACKET
(define (make-counter)
  (let ([count 0])
    (lambda ()
      (set! count (+ count 1))
      count)))

(define c1 (make-counter))
(define c2 (make-counter))
(c1) (c1) (c1)   ; 1 2 3
(c2)             ; 1   a separate count

The variable count is not accessible from anywhere else: no global, no field. Each counter has its own.

Independent counters

A bank account with several operations

To expose more than one operation, return a function that dispatches on a message symbol. This is the classic "message-passing" style:

Message-passing account

The balance is hidden: the only way to reach it is through the returned function. Closures and objects are two views of the same idea: data bundled with the operations on it.

Common mistakes

  • Expecting a copy of a variable. A closure captures the variable, not its value at creation time. If something later does set! on it, the closure sees the new value.
  • Forgetting to call. make-counter returns a function; you must call that returned function (c1), not c1.
  • Wrong parentheses. ((lambda (x) x) 5) calls it; (lambda (x) x) 5 is two separate expressions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ((lambda (x) (* x x)) 5) return?

    The lambda creates a function that is immediately called with 5.
  2. 2. What is a closure?

    A closure bundles code with its lexical environment, so it keeps using those variables later.
  3. 3. After (define add5 (make-adder 5)), why does (add5 3) still work after make-adder returned?

    The inner lambda holds a reference to the environment of that make-adder call.
  4. 4. Two counters from make-counter: what does calling c1 twice then c2 once give for c2?

    Each make-counter call creates its own count, so c2 starts at 1.

Summary

  • lambda creates an anonymous function value; define just names one.
  • Functions can be passed, returned and stored: that is what higher-order means.
  • A closure carries its surrounding variables, so returned functions remember where they came from.
  • Closures with set! give private, per-instance state.
  • Message passing with a dispatch function is an object system in miniature.

Next: map, filter and fold