Named arguments: solutions, ideas [Was: Re: d assigns name Philosophy]

bearophile bearophileHUGS at
Fri May 1 05:36:30 PDT 2009

Andrei Alexandrescu:
> I'm not very sure. That would suggest using exceedingly common names 
> (the, on, go, do, be, and, use...) which are often imprecise because 
> they are used in a variety of contexts (hence their frequency). I often 
> prefer a word that has a precise meaning.

Some compromise can be found and adopted. I agree that using 2-letter names everywhere will cause troubles.
On the other hand there are name that are too much long and bad, for example the most used sort will probably be the SwartzSort that is too much long and difficult to write for me (I am so far unable to remember the correct spelling), so I'll probably have to use an alias, like keySort or ssort. I also use put/putr to print strings, because I use them all the time to debug, etc. Other examples exists in Phobos2.

Regarding the sort/SwartzSort of Phobos2, they can be merged into a single function template named "sort", you can tell it what algorithm to use giving the cmp or key function literal.

You can do that adding named arguments to templates too (not just adding to functions, as in C#).

Time ago I have shown here a problem regarding the implementation of named arguments in delegates/function pointers. Now I think this problem can be solved adding the names of the arguments too (and not just their type) to the type signature of the function/delegate. So the type system is able to tell them apart. I think this solves the problem and allows to add named arguments in D2 (and there is no equivalent of run-time delegates/function pointers for templates, so there are no problems caused by this if you want to implement named arguments to templates).


Regarding named arguments (both of templates and functions) there is another small related idea/feature that may be added: a way to specify that you must use the name when you want to use a certain argument. So you are forced to write cmp:"..."  or key:"..." where you do the call (if a named argument has a default value then you can ignore it).

I don't know yet what syntax to use to do this. A first possible idea is to add "#" before the names of the arguments that you are forced to use named:

A function with two normal arguments, and two forced named arguments, where the second has a default value:
foo(int a, int b, int #c, int #d=1) { ... }

You can perform a call to foo() like this:
foo(1, 2, c:3)
foo(1, b:2, c:3)
foo(a:1, b:2, c:3)
foo(1, 2, c:3, d:4)

but not like this:
foo(1, 2, 3)
foo(1, 2, c:3, 4)
foo(1, 2, 3, d:4)
Because the names "b" and "c" must be given explicitly when they are used.

I don't know if this is overkill (something similar is used in the key/cmp arguments of Python3 sort()/sorted()).


More information about the Digitalmars-d mailing list