Higher Order Functions & Lexical Closures
Higher order functions are, in the simplest sense, functions that can be treated as if they were data objects. In other words, they can be bound to variables (including the ability to be stored in collections), they can be passed to other functions as parameters, and they can be returned as the result of other functions. Due to this ability, higher order functions may be viewed as a form of deferred execution, wherein a function may be defined in one context, passed to another context, and then later invoked by the second context. This is different from standard functions in that higher order functions represent anonymous lambda functions, so that the invoking context need not know the name of the function being invoked. Lexical closures (also known as static closures, or simply closures) take this one step further by bundling up the lexical (static) scope surrounding the function with the function itself, so that the function carries its surrounding environment around with it wherever it may be used. This means that the closure can access local variables or parameters, or attributes of the object in which it is defined, and will continue to have access to them even if it is passed to another module outside of its scope. Among the languages we're considering, Smalltalk and Ruby have supported both higher order functions and lexical closures from the beginning in the form of blocks. A block is an anonymous function that may be treated as any other data object, and is also a lexical closure. Eiffel has recently added support for higher order functions using the "agent" mechanism. The inline variant of Eiffel agents forms a lexical closure. Python, which has long supported higher order functions in the form of lambda expressions, has recently added support for closures using its improved support for nested static scopes. While neither Java nor C++ support higher order functions directly, both provide mechanisms for mimicking their behavior. Java's anonymous classes allow a function to be bundled with an object that can be treated much as a higher order function can. It can be bound to variables, passed to other functions as an argument, and can be returned as the result of a function. However, the function itself is named and thus cannot be treated in a generic fashion as true higher order functions can. C++ similarly provides partial support for higher order functions using function objects (or "functors"), and add the further benefit that the function call operator may be overloaded so that functors may be treated generically. Neither C++ nor Java, however, provide any support for lexical closures. Visual Basic provides no support for either higher order functions or lexical closures, nor is there any apparent mechanism for providing similar behavior.