kids encyclopedia robot

Closure (computer science) facts for kids

Kids Encyclopedia Facts

A closure in computer science is like a special function that remembers its surroundings, even after those surroundings are gone. Think of it as a function that carries its own little "backpack" of information. This backpack holds specific pieces of data, called bound variables, which the function can use whenever it runs. This way, the closure keeps these important pieces of data safe in memory.

The idea of closures was first named by Peter J. Landin in 1964. They became very popular after 1975, especially with the Scheme programming language. Today, many modern programming languages use closures.

Sometimes, people confuse closures with anonymous functions. An anonymous function is simply a function without a name. While many languages have both, an anonymous function is only a closure if it remembers its own environment and bound variables. A named function can also be a closure if it does the same.

How Closures Work with Functions

In programming, values can be numbers, text, or more complex data structures. Some programming languages treat functions as "first-class values." This means you can do many things with functions, just like you can with numbers. You can pass them into other functions, return them from functions, or store them in variables. Functions that work with other functions in this way are called higher-order functions. Most languages that have first-class functions also have closures.

Let's look at an example using a programming language called Scheme:

(define (best-selling-books threshold)
  (filter 
    (lambda (book) (>= (book-sales book) threshold))
    book-list))

In this code, the `lambda` part creates a small, unnamed function. This function needs to know the `threshold` value to decide if a book is a best-seller. The `threshold` is a free variable here, meaning its value isn't set inside this small function itself.

When the `best-selling-books` function runs, it creates a closure for that `lambda` function. This closure "captures" the `threshold` value from its surroundings. Then, the `filter` function uses this closure to check each book. Because the closure remembers `threshold`, it can use that value every time it checks a book.

Here's the same idea in JavaScript, another popular language:

// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
  return bookList.filter(
      function(book) { return book.sales >= threshold; }
    );
}

JavaScript uses the word `function` instead of `lambda`, but it works in a similar way. The inner function remembers the `threshold` value from the `bestSellingBooks` function.

A function can even create a closure and give it back as a result. This means the returned function carries its remembered data with it.

In Scheme:

(define (derivative f dx)
  (lambda (x) (/ (- (f (+ x dx)) (f x)) dx)))

In JavaScript:

// Return a function that approximates the derivative of f
// using an interval of dx, which should be appropriately small.
function derivative(f, dx) {
  return function(x) {
    return (f(x + dx) - f(x)) / dx;
  };
}

In these examples, the `derivative` function creates and returns another function. The returned function is a closure. It remembers the values of `f` and `dx` from when `derivative` was called. Even after `derivative` finishes, the returned closure still has access to `f` and `dx`. In languages without closures, these values would usually be lost.

Closures don't always have to be made with unnamed functions. For example, in Python, you can define a named function inside another function, and it will also form a closure:

# Return a function that approximates the derivative of f
# using an interval of dx, which should be appropriately small.
def derivative(f, dx):
    def gradient(x):
        return (f(x + dx) - f(x)) / dx
    return gradient

Here, the `gradient` function becomes a closure, remembering `f` and `dx`.

What Closures Are Used For

Closures are very useful in programming for many reasons:

  • Customizing Behavior: Software designers can let users change how their programs work. For example, a function that sorts things can take a closure as an input. This closure would tell the sorting function how to compare items based on what the user wants.
  • Creating Control Structures: Closures can delay actions until they are needed. This allows programmers to build their own ways to control the flow of a program, like custom "if/then/else" statements or "loops."
  • Private Communication: Several functions can share the same closure environment. This lets them "talk" to each other privately by changing the data stored in that shared environment.

Here's an example in Scheme showing how closures can communicate:

(define foo #f)
(define bar #f)

(let ((secret-message "none"))
  (set! foo (lambda (msg) (set! secret-message msg)))
  (set! bar (lambda secret-message)))

(display (bar)) ; prints "none"
(newline)
(foo "meet me by the docks at midnight")
(display (bar)) ; prints "meet me by the docks at midnight"

In this example, `foo` and `bar` are two closures that share the `secret-message` variable. `foo` can change the message, and `bar` can read it.

  • Building Object Systems: Closures can also be used to create object-like systems, where data and the functions that work on that data are bundled together.

See also

Kids robot.svg In Spanish: Clausura (informática) para niños

kids search engine
Closure (computer science) Facts for Kids. Kiddle Encyclopedia.