|
|
||
Alexander Schunk's BlogMy View on Closures: Part 2Posted by alexanderschunk on January 20, 2008 at 05:09 AM | Comments (4)No more symbols please>In my last Blog i did make some suggestions to get rid of the redundand => syntax of closures. I suggested to use := and to invent a keyword i.g. block or function to highlight the fact that closures are functional objects - basicall Neil Gafter regards them as equivalent to anonymous methods however i think there is no strict distinction in Gafters proposal wheather a closure is a pure function or an object According to Neil Gafter, a closure object needs to be invoked by calling the invoke() method for a particular closure. The invoke method can have parameters i.g.:
{ int x => x + 1 } //closure definition
{ int x = > x + 1 }invoke(10); //call closure with 10 as parameter
So if a closure is a function in this case - besides the fact that its also an object - a closure object - then i think it would make sense to declare this whole block of statemens as a function:
function { int x => x+ 1}(int);
In my last Blog i said that the => symbol is redundant and suggested to use := as a variation of =. With this variation the closure would be written as:
function{
int x := x+ 1;
}(int);
//call closure with 10 as argument
function{ int x:=x+1 }(10);
This syntax could also be used to simply define getters that return values:
function {int x:=10;}(); //always returns 10
int s = function sum{int x, int y := x+y }(3, 5); //call sum with 3 and 5 as parameters
Local variablesAlso its possible to declare local variables in closures:
function{
int j = 0;
int i=3;
switch(i){
//some switch statements
case 1: j++;
case 2: j--;
}
}();
Thus using a function keyword makes clear that a closure is both a function and an object that can be invoked. The invocation is executed by adding the () parantheses to the statement. Bookmark blog post: CommentsComments are listed in date ascending order (oldest first) | Post Comment
| ||
|
|