Named arguments

Bastiaan Veelo Bastiaan at Veelo.net
Wed Oct 25 12:40:47 UTC 2017


On Wednesday, 25 October 2017 at 08:09:52 UTC, Gary Willoughby 
wrote:
> On Tuesday, 24 October 2017 at 17:30:27 UTC, Andrey wrote:
>> Hello, why there are no named arguments for functions like, 
>> for example, in kotlin i.e.:
>>
>>> int sum(in int a, in int b) {
>>>     return a + b;
>>> }
>>>
>>> sum(a = 1, b = 2);
>
> This has been discussed to death:
>
> http://forum.dlang.org/post/n8024o$dlj$1@digitalmars.com
>
> and you can do it as a library so no need to go in the language:
>
> https://github.com/CyberShadow/ae/blob/master/utils/meta/args.d

Thanks for that link. Unaware of CyberShadow's work (which 
probably is of better quality) I just had a go:

```
void foo(int one, int two, double three, string four) {
     import std.stdio;
     writeln("one=", one, "; two=", two, "; three=", three, "; 
four=", four);
}

int first = 1;
void main()
{
     // Ordinary:
     foo(first, 2, 3.0, "4");    // Prints one=1; two=2; three=3; 
four=4
     // Named arguments:
     named!(foo, "four", "4",
                 "two", 2,
                 "one", first,
                 "three", 3.0);  // idem
}

import std.traits;
auto named(alias F, args...)() if (isFunction!F) {
     import std.meta;

     alias names = Stride!(2, args[0..$]);
     alias values = Stride!(2, args[1..$]);

     bool cmp(alias valueA, alias valueB)() {
         import std.algorithm.searching;
         return countUntil([ParameterIdentifierTuple!F],
                           names[staticIndexOf!(valueA, values)]) <
                countUntil([ParameterIdentifierTuple!F],
                           names[staticIndexOf!(valueB, values)]);
     }

     return F(staticSort!(cmp, values));
}
```

Not battle tested, but it works here. There is a limitation that 
the variable "first" cannot be local, but people better at this 
stuff may be able to remove that.

Bastiaan.


More information about the Digitalmars-d mailing list