Why Ruby?

JRM a at b.com
Sat Dec 18 17:24:43 PST 2010


On Sat, 18 Dec 2010 16:01:37 -0800, Walter Bright wrote:

> Simen kjaeraas wrote:
>> The problem of D's lambda syntax is it is optimized for longer
>> functions. Usually, the delegates I write are one line long. I cannot
>> see that this syntax collides with anything at the moment, but feel
>> free to enlighten me:
>> 
>> { => 4; }
>> { a => 2*a; }
>> { a, b => a>b; }
>> { => @ + @; } // turns into { a, b => a + b; }
>> 
>> 
> If size and simplicity of typing are critical, are those really better
> than:
> 
>    "a>b"
> 
> ?

I agree that those aren't really much better.
This entire discussion seems a little odd to me.  People are trying to 
find a way to more easily write lambda's, focusing in particular on 
single expression lambda's.  This happens to be the one case D already 
has a short syntax for.

In order to support lazy, D already allows an expression to be implicitly 
converted to a delegate returning either void or the type of the 
expression.  This covers the case of lambda's taking no arguments, and 
happens to be shorter than any of the proposed syntaxes.

The only issue with this is support for delegates taking arguments.  To 
do that, I suggest D define numbered placeholders, similar to those found 
in C++ (tr1 and 0x) and std.bind.  When found in an expression that is 
being implicitly cast to a delegate, the placeholders will represent the 
delegate's arguments.

In your "a>b" example, the expression @1>@2 would be converted to the 
delegate:

bool delegate(arg1, arg2) { return arg1>arg2; }

So in actual use, instead of writing:
sort!((a, b) { return a > b; })(x);
you could write:
sort!(@1>@2)(x);

This would make a single-expression lambda almost identical to the string-
based expressions currently being used.  It is similar to the Scala 
example mentioned earlier in this thread (i.e. _ > _), but it allows for 
arbitrary use of the arguments without resorting to named parameters.  
For instance, the Scala form doesn't allow you to use a single parameter 
more than once and it requires the arguments to be used in order.  With 
this syntax, we could easily do things like @1*@1 or @2- at 1 without 
resorting to named parameters.

I think this idea (or something similar) is worth consideration.  It is 
simply a small extension to an already existing feature that would give D 
a terser syntax for lambda's than most of the other languages we've been 
discussing.


More information about the Digitalmars-d mailing list