CSC/ECE 517 Fall 2010/ch1 1b YL
Closures in Ruby vs. closures in other languages
Closures
Before discussing semantic and implementation differences of closure implementation in different languages, closures should be discussed first.
A closure is a first-class function with free variables that are bound in the lexical environment. Closures:Wikipedia
Such a function is said to be "closed over" its free variables. In this definition first-class function is the function which is treated as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions. [1]
So closure can be explained as nothing but the behavior or in programming language function which can be passed around like any other argument and still remembering the original context where these functions are declared first. This way it breaks out of the standard function concept where the variables inside functions can be referenced within the scope of the function. However, in closures these variables can be referred out of the scope of the local functions. This ability of accessing original context makes closure different from normal objects.
Closure concept can be illustrated with the example in JavaScript.
// Return a list of all employees with at least 'threshold' salary.
function highlyPaidEmployees(threshold)
{
return empList.filter( function (emp) { return emp.salary >= threshold; } );
}
In above javascript function highlyPaidEmployees
, another anonymous function is defined. This function is passed to the Array.filter
method with free variable threshold. This free variable is assigned the value that is passed during the function call of highlyPaidEmployees. Thus the anonymous function defined inside is called repeatedly by filter method with free variable threshold having assigned the value passed to the highlyPaidEmployees. This follows both the properties defined in the closure definition. One is that the function is passed as an argument and function is able to access free variable out of its context.
Closure is supported by many languages. Ruby is famous for extensive use of closure. In next few sections comparison of closure implementation is different languages is done.
Basis of differences in implementations of closure
Even though many languages support closure concept there are significant differences in closure implementation in different languages. Some languages support closure concepts partially. Considering all these following are the point on the basis of which closures in different languages differ.
- First-class function - Whether language supports passing function as an argument
- Out of context reference - Whether language supports refering variable out of scope of its context
- Copy of variable or reference to a variable location - If language supports Out of context reference of variable then how is it implemented. Whether variable value is copied or same copy of variable is referred.
- Function currying - It is the technique by which function with multiple arguments can be called as a function with chain of functions each with single argument. Function Currying Some languages support it and some not.
- Control structure using closure - Whether language supports closure for control structure or not.
- less lines of code - If language supports control structure using closure then it reduces lines of code considerably.
Closures in Ruby
In Ruby closures can be implemented using Blocks or Proc objects.
Blocks =
Blocks are like closures, because they can refer to variables from their defining context. Within the body of the invoked method, the code block may be called using the yield keyword. Following example explains the concept of blocks in Ruby.
def thrice yield yield yield end x = 5 puts "value of x before: #{x}" thrice { x += 1 } puts "value of x after: #{x}"
In above example x is incremented every time yield is called. Every yield call calls block {x += 1}
and it remembers value of x between calls. Also even though x is not defined in thrice method block accesses x from the location where this block was defined. Thus A block is a closure as it remembers the context in which it was defined, and it uses that context whenever it is called.
Proc =
Ruby’s blocks are chunks of code attached to a method that operate in the context of the caller. Blocks are not objects, but they can be converted into objects of class Proc. There are three ways of converting a block into a Proc object.
1. By passing a block to a method whose last parameter is prefixed with an ampersand. That parameter will receive the block as a Proc object.
def meth1(p1, p2, &block) puts block.inspect end meth1(1,2) { "a block" } meth1(3,4)
2. By calling Proc.new, again associating it with a block.
block = Proc.new { "a block" }
3. By calling the method Kernel.lambda
block = lambda { "a block" }
Closures in other languages
Closures in Lisp
Closures in ML
Closures in C
The C language does not support closures directly, but it has some extensions which add closures like functionality. Nested functions are similar to closures.
A nested function is a function defined inside another function. It's scope is limited to the enclosing function. The nested function can access all the variables of the containing function that are visible at the point of its definition. This is called lexical scoping.
int arrayProcess (int *array, int offset, int size) { int arrayAccess (int *array, int index) { return array[index + offset]; } int i; /* ... */ for (i = 0; i < size; i++) /* ... */ access (array, i) /* ... */ }
Here the inner function arrayAccess can refer to outer function's variable 'offset'.
The nested function can be called from outside the enclosing function by passing its address to another function:
It is possible to call the nested function from outside the scope of its name by storing its address or passing the address to another function:
int arrayProcess (int *array, int size) { void store (int index, int value) { array[index] = value; } intermediate (store, size); }
Here, the address of the function store is passed to the function intermediate as an argument. So, intermediate can call store with index and value arguments. But, intermediate can call store so long as the enclosing function arrayProcess does not exit.
It is not safe to call the nested function through its address after its enclosing function is exited. But, if the nested function does not refer to anything that has gone out of scope, then it will work.
Another closure like feature C language provides is function pointers.
int addition(int a, int b) { return a + b; }
// <ptr2Func> is a pointer to a function which takes two int values and returns an int void getPoniter(int (*ptr2Func)(int, int)) { int result = (*ptr2Func)(10,20); // call using function pointer printf("Result = " + result); }
void passPoniter() { int (*ptr2Function)(int, int) = NULL; ptr2Function = &addition; //& is optional here but prefered getPoniter(ptr2Function); }
Function pointers are nothing else than variables. In the code above, ptr2Function is pointer to function addition which takes two integers and returns one integer. It is then passed to another function getPointer(), which can then call the function addition using that pointer. Function pointer can be passed as an argument which is one of the desired property of the closures.
Closures in C++
C++ supports function pointers like C as well as it has some libraries which provide lambda expressions.