August 09, 2010
Hello,

I have a few suggestions about function parameters in D, mostly from my experience with Python.

First, named arguments would be useful.  For example:

int add (int a, int b) {
   return a + b;
}

And then you call it with:

add(a = 3, b = 7)

This is mostly helpful because you can be more explicit, and if you only want the last default parameter to be different, you don't have to fill in the rest just so you can make the last one different.

It also helps readability, for example openFile("test", readonly = true) makes a lot more sense than
openFile("test", true).

This works well in Python because an assignment is its own kind of statement and cannot be used as an expression. This is mostly so you don't make the mistake of writing an if statement with only one = and seeing your code break without warning.

It also makes default parameters more useful than annoying, for example:

string wordwrap (string str, int width = 75, string break = "\n", bool cut = false) { ... }

And you could just say:

wordwrap("Hello world!", cut = true);

Instead of:

wordwrap("Hello world!", 75, "\n", true);

Where it's hard to tell what's happening anyway.

Another suggestion is concerning variadic arguments.

Second are variadic functions.  As an example, in Python, a variadic function could look like this:

def max(*numbers):
  largest = 0
  for number in numbers:
     if number > largest:
        largest = number
  return largest

Then you can call max(5, 3, 7) and within the function the variable numbers becomes an array filled with the values 5, 3, and 7.

I think this type of argument passing would fit well into D, because pointers shouldn't be necessary, especially for something simple like this.  The language also natively supports dynamic arrays, which makes this very sensible as opposed to pointers.

Another useful feature is that of unpacking an array.  If you have an array of numbers and you want to call max() on them, you could write max(*array), and then array would be expanded as if all of its elements were passed as individual arguments.

Python also supports dictionary (associative array) parameters:

def foo(**dictionary): ...

And you could call it like foo(x = 3, a = 5).  Inside the function, the dictionary parameter is a dictionary of the form {"x": 3, "a": 5}.  I imagine the syntax different in D, but the same principles apply.

I'm not sure about the syntax that would be best for all this.  Mainly, the * would conflict with the pointer definitions (which these do partially replace).  But you could use an argument trait like:

int max (var int x[]) { ... }

With "var" as in "variadic."  Unpacking arrays into the argument is a different question though.

Maybe the nicest thing about this is type checking, much better than pointers.

Sincerely,

Alec Newman