| ||
> What is a closure? I keep reading this word in programming, but never got a good explanation. People always come up with the generator case, and I think that's the worst way of all to show off closures. Where they really come in handy is introducing lexical scoping. Lexical scoping just means that the environment is defined by the context in the code, not in runtime. An example in Common Lisp:
This is a function called ADD-TO-LIST that takes a list and adds a number to each of its elements. DEFUN defines a function, MAP applies a function to each element of a list, and LAMBDA defines an anonymous function. Now consider the anonymous function - it references both X, a parameter to the function, and NUMBER, which is a parameter to add-to-list. It must have access to NUMBER regardless of the context in which it's called. So it's placed into a closure, where all the variables in its environment are available. In that way, MAP doesn't have to worry about providing access to variables. This is the primary advantage closures have over other function-variable patterns, like function pointers or functors. Anonymous functions declared in-place "just work."
|
| Posting comment |
To prevent comment spam, you must type a passcode into the passcode box. Right now, the passcode is elbow. |
