Passing function parameters by name

David Wilson dw at botanicus.net
Tue Dec 4 07:07:54 PST 2007


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
>



More information about the Digitalmars-d mailing list