2012-03-08

What's “closure” in Programing Language?

Perm URL with updates: http://xahlee.org/UnixResource_dir/writ/closure.html

Closure means a few things.

  1. In non-programing contexts, it means something is “closed”, or, a sense of completeness. For example: “I'm returning to my hometown for a sense of closure.”.
  2. In math, algebra, it means a property of a algebraic structure, namely: a function with input from elements of the set, whose result is always also a element in the set. (i.e. the set is closed under this operation) For example, it's common to hear: “the addition operation is closed over integers.”. It means, adding 2 integers results in a integer. Division, for example, is not closed under integers. That is, diving 2 integers may result in something that is not a integer. e.g. fraction.
  3. In programing, it means a mechanism/feature in a language such that a function/subroutine can maintain a state. (in a clean way. e.g. without using global var)
  4. A function/subroutine that maintains states using the above feature.

and, of course, the Clojure, spelled with a “j”. A functional programing language of the lisp family.

For a example in python, see: Python: Function with State (closure).