Anonymous function syntax

Robert Jacques sandford at jhu.edu
Sat Sep 24 11:02:21 PDT 2011


On Sat, 24 Sep 2011 03:23:13 -0400, Alex_Dovhal <alex_dovhal at yahoo.com> wrote:

> "Robert Jacques" <sandford at jhu.edu> wrote
>> Well, actually, this is Jason's proposal and it's explicitly for a
>> std.algorithm style, by convention, super-short lambda syntax. i.e.
>> primarily for one liners and std.algorithm. If you go the
>> comma_separated_params, then I think the a => a+x; route is better.
>
> Maybe, x=>f(x) syntax isn't bad, but in most simple and most oftern cases --
> \a*a is 4 chars while a=>a*a is 6 chars. Then \(x,y)x+y is 9 chars,
> (x,y)=>x+y is 10 chars, while \a+b is still 4 chars.

I'm not sure you understand the main point: there are multiple ways to define a lambda. So \a+b and (a,b)=>a+b could co-exist together just fine.

>> Actually, I made a error in my final example as each lambda must be
>> terminated somehow. i.e. with a semi-colon:
>>
>> reduce!\a+b;(map!\a+b;([1,2,3,4))
>
> No. Those semicolons in the middle of expression looks strange.
> Compiler can't determine that expression following ! has ended so you must
> use !()

How is !() different from !\; ? \; is for literals. Hence, it would work just like !"a+b".

>  int b =  5;
>  reduce!(\(a,b)a+b)(map!(\(a)a+b)([1, 2, 3, 4]))
>
>> As for hijacking, I think by-convention lambdas should be disallowed if a
>> or b are used in the lambda and are already defined in the namespace. In
>> those cases, you'd have to revert to a more general syntax, i.e.
>>
>> reduce!"a+b"(map!(a => a+b)([1,2,3,4)));
>
> In such not often cases one can even use long lambdas
>  reduce!"a+b"(map!((int a){return a+b;})([1,2,3,4])));

Which is what I was suggesting, although I used the most concise syntax: a => a+b
Also, as non-trivial use of algorithm often results in 120+ line widths, today using the "a+b" style syntax, conciseness is golden.

> BTW, existing usage of strings ("a+b") is second shortest afrer \a+b and is
> properly delimited.
> maybe allowing several variations of  \lambdas
> (1) \a+b - automatic names, shortest lambda possible, easy to read. for use
> when it can be easily delimited e.g  list_comprehent!(\a*a, \a!=1)(a)
> (2) \{a+b} - automatic names, to properly delimit lambda, usefil in
> map!\{a*a}(a), eh, you are rigth here compiler can omit ! -- map\{a*a}(a)
> (3) \(x)x+a -- explicit names, to prevent name hijacking.
> (4) \(x){x+a} - explicit names and properly delimited
> in (1) and (3) no comma allowed, as it can cause ambiguities.
>
>


More information about the Digitalmars-d mailing list