Named arguments via struct initialization in functions

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 6 11:10:50 PST 2016


On Sun, 06 Mar 2016 17:35:38 +0000, Seb wrote:

> Hey all,
> 
> I wanted to relive the discussion on named arguments and ping for its
> current status.

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.

> 2) allow struct inits in functions - e.g. fun({x: 4})

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.

Anyway, if it works, it's an improvement. And you only need explicit type 
marking at the top level; it's unambiguous after that.


More information about the Digitalmars-d mailing list