Passing function parameters by name

Artyom Shalkhakov artyom.shalkhakov at gmail.com
Tue Dec 4 09:15:18 PST 2007


David Wilson Wrote:

> On 12/4/07, bearophile <bearophileHUGS at lycos.com> wrote:
> > Artyom Shalkhakov:
> > >     foo( b : 2.5f, a : -3 ); // sort of struct initializer
> >
> > Python uses =
> >
> > foo(b=2.5f, a=-3);
> >
> > This is a very useful feature, I use it often in Python. But if you try to translate this Python code:
> >
> > from sys import argv
> > def a(c="A"): print c
> > def b(c="B"): print c
> > l = [a, b]
> > if argv[1] == "1": l.reverse()
> > l[1]()
> >
> > to D/C++ you can find a problem, becasue the "A" and "B" must be associated with the function. And the function must know what parameters aren't actually given to it. So you may need to silently pass an array of booleans too (and uint/ulong suffices) that encode what parameters you have actually given to the function (there are other solutions, based on pointers, but they seem even slower to me).
> 
> 
> This one is pretty close to my heart too, but I can't quite decide
> what the resulting feature would look like in D. I made an effort to
> port Python's awesome ElementTree XML library to D, but found most of
> its convenient syntax was lost because D doesn't support named
> arguments.
> 
> A further twist to this is Python's ability to take arbitrary named
> arguments and build an associative array from them ("dict").
> Implementing this feature would probably mean tight integration with
> AA literal syntax for uniformity's sake, but I couldn't come up with a
> syntax worth proposing.
> 
> Desirable:
>  - Ability to specify non-default parameters after default parameters.
>  - Ability to lazy-build an associative array argument to a function,
> without using AA literal syntax.
> 
> 
> Rough idea:
> 
> void foo(int a, bool b = true, bool c = false, char[][char[]] args);
> foo(0xcafebabe, c: true, strangeArg: "hello", otherArg: "world");
> 
> 
> Except I'm sure there's a plethora of things I've forgotten about
> (interactions with templates for example?)
> 
> 
> David.
> 
> 
> >
> > Bye,
> > bearophile
> >

I'm not into getting D so close to Python... I think that the default-parameter-values should remain as-is, with the added ability to address parameters by their name.

I suggest looking at D's struct initializers. (Make the process of initializing an array and calling a function more 'uniform'.)



More information about the Digitalmars-d mailing list