Possible enhancement: Concise return statements

Mafi mafi at example.org
Mon Aug 15 08:04:47 PDT 2011


Am 15.08.2011 16:01, schrieb Jacob Carlborg:
> On 2011-08-15 12:54, Timon Gehr wrote:
>> Currently, when using delegates in D, there is 'return' all over the
>> place.
>> Eg:
>> map!((a){return a*foo(a);})(arr);
>>
>> Many delegates consist of only one return statement. Writing 'return' is
>> rather inconvenient and adds to the general noise.
>>
>> Now, I would like to propose to enhance the language in the following
>> way:
>>
>> 'When the last ExpressionStatement in a function body is missing the
>> ';', it is implicitly returned.'
>>
>> The example above would become:
>>
>> map!((a){a*foo(a)})(arr);
>>
>> Multi-statement delegates would also be supported:
>> {auto y=x;++x;y}();
>>
>> Probably, it would be best to disallow to use both forms of return
>> statement simultaneously:
>>
>> {if(x) return y; z} // error
>>
>> I feel that this would add much to the language for both code
>> readability and pleasure of writing code, especially in a functional
>> style. As it is a purely additive change (currently, such code is always
>> a syntax error), no existing code would be broken.
>>
>>
>> (One indirect benefit would be that we could then require lazy arguments
>> to be pure. Call by name would then be implemented by eg:
>>
>> int x;
>> foo({x<100},{x++}); // it is evident at the call site what is going on)
>>
>>
>>
>> Any thoughts on this?
>
> Yes, please. In fact I would like that the last expression in all
> functions and delegates to be automatically returned.
>
> When we're talking about improving the delegate syntax I would like to
> have these two syntaxes for delegates:
>
> foo(x => x * x)
>
> and
>
> foo(x) {
> x * x
> }
>

I personally don't like number one but that's subjective.
The second has a serious problem: it makes the grammer context 
sensitive. You can't distinguish such a call from a local function 
definition.
Therefore I suggest:
foo(x) do (...){
...
}

'do' is already a keyword but only once ten years used for a do...while 
loop. If the functions are named correctly it reads perfectly:
when!SomeEvent do (ev) {
}

where when is:
void when(T : Event)(void delegate(T) reaction) {...}



More information about the Digitalmars-d mailing list