Named arguments via struct initialization in functions

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 7 03:06:13 PST 2016


On Sunday, 6 March 2016 at 19:10:50 UTC, Chris Wright wrote:
> On Sun, 06 Mar 2016 17:35:38 +0000, Seb wrote:
>
>> [...]
>
> We want something to let people provide arguments sparsely and 
> unambiguously, and if possible in arbitrary order. The existing 
> DIP just lets you provide compiler-checked annotations to 
> verify the parameter names match your expectations, assuming 
> the writer of the function chose to allow it.
>
> Nobody much liked it. I've got a draft DIP on my hard drive to 
> provide actual named arguments but haven't gotten around to 
> proposing it.
>
> There was considerable disagreement on whether the function 
> parameters should be explicitly marked in order to use them as 
> named or not. Scala, Python, C#, Ceylon, and I believe Ada 
> don't require you to mark them. Ruby and Dart require you to 
> mark them.
>
> There are a couple other interesting decisions regarding named 
> parameters, but nobody much considered them during the 
> discussion. Ceylon's the most permissive example.
>
>> [...]
>
> I looked into this a bit. I've got another draft DIP for it on 
> my hard drive. There are two obvious ambiguities:
>
>   struct A { int x; long y; }
>   struct B { int x; string y; }
>   void foo(A a) {}
>   void foo(B b) {}
>   foo({x: 1});
>
> There's no way to tell which overload to invoke.
>
> Then let's say I added:
>   void foo(void delegate() dg) {}
>   foo({});
>
> That could be a default-initialized struct of type A or B, or 
> it could be a no-op delegate.
>
> You can resolve that with a slightly different syntax:
>
>   foo(A{x: 1});
>
> I think I noticed an ambiguity with that, too, but I can't 
> recall now. I failed to write it down in any case.

The compiler should detect that this call is ambiguous and would 
not allow it.

To resolve the ambiguity, the user can write:
foo(A{ x: 1 });
foo(B{ x: 1 });
foo(() { });
foo(delegate void() { });

Which I think is a very reasonably requirement.

Do you have any other examples of ambiguity that can't be easily 
resolved?

> Anyway, if it works, it's an improvement.
Yep.

> And you only need explicit type marking at the top level;
> it's unambiguous after that.

I'm not sure what you mean by "explicit type marking at the top 
level".






More information about the Digitalmars-d mailing list