Lambda syntax, etc
bearophile
bearophileHUGS at lycos.com
Wed Feb 4 02:57:01 PST 2009
I've taken a look at the syntax for lambda in other C-like languages.
This is from Functional Java:
http://functionaljava.org/examples#Array.filter
In Functional Java you can write this D syntax:
(int i, int j) { return i % 3 == j; }
as:
{ int i, int j => i % 3 == j }
It's shorter and less cluttered/noisy than the D syntax, and it doesn't require more type inferencing (but I think you can't put statements there, so it's less powerful).
With that Java syntax extension you can write:
final Array<Integer> a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
final Array<Integer> b = a.filter({int i => i % 2 == 0});
In D (with dlibs) it is:
auto a = [97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42];
auto b = a.filter((int i){return !(i % 2);});
With std.algorithm it may be a bit shorter.
In Python:
a = [97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42]
b = [x for x in a if not(i % 2)]
C#2 has lambdas, and C#3 adds closures and more type inferencing, so C#3+ supports the following syntaxes:
(int i) => { return i % 3 == 1; } // C#2
i => i % 3 == 1 // C#3
i => { return i % 3 == 1; } // C#3, with statements too
To define a delegate o delegate closure:
Func<int> foo = i => { return i % 3 == 1; };
Func<int> foo = i => i % 3 == 1;
Func<int> bar = () => 2;
But this isn't allowed:
Func<void> bar = () => 2;
Few comments I have copied relative to C#3:
>C# it automatically generates either an anonymous class or an anonymous method for the closure depending on if the function needs to close over the local scope or not.<
>When such an expression is evaluated, it produces a function-object which can be called with the arguments implied by the LambdaList, and whose body expressions have access to all the lexical variables that are visible at that point. The ones that are outside of the expression, whose bindings were established before it was created, are captured. This is why the resulting object is called a LexicalClosure.<
>Even when the code uses the closure more than once, the compiler creates only one instance of the closure. That environment is reused each time.<
Bye,
bearophile
More information about the Digitalmars-d
mailing list