Programming in D – Tutorial and Reference
Ali Çehreli

Other D Resources

Variable Number of Parameters

This chapter covers two D features that bring flexibility on parameters when calling functions:

Default arguments

A convenience with function parameters is the ability to specify default values for them. This is similar to the default initial values of struct members.

Some of the parameters of some functions are called mostly by the same values. To see an example of this, let's consider a function that prints the elements of an associative array of type string[string]. Let's assume that the function takes the separator characters as parameters as well:

import std.algorithm;

// ...

void printAA(string title,
             string[string] aa,
             string keySeparator,
             string elementSeparator) {
    writeln("-- ", title, " --");

    auto keys = sort(aa.keys);

    // Don't print element separator before the first element
    if (keys.length != 0) {
        auto key = keys[0];
        write(key, keySeparator, aa[key]);
        keys = keys[1..$];    // Remove the first element
    }

    // Print element separator before the remaining elements
    foreach (key; keys) {
        write(elementSeparator);
        write(key, keySeparator, aa[key]);
    }

    writeln();
}

That function is being called below with ":" as the key separator and ", " as the element separator:

void main() {
    string[string] dictionary = [
        "blue":"mavi", "red":"kırmızı", "gray":"gri" ];

    printAA("Color Dictionary", dictionary, ":", ", ");
}

The output:

-- Color Dictionary --
blue:mavi, gray:gri, red:kırmızı

If the separators are almost always going to be those two, they can be defined with default values:

void printAA(string title,
             string[string] aa,
             string keySeparator = ": ",
             string elementSeparator = ", ") {
    // ...
}

Parameters with default values need not be specified when the function is called:

    printAA("Color Dictionary",
            dictionary);  /* ← No separator specified. Both
                           *   parameters will get their
                           *   default values. */

The parameter values can still be specified when needed, and not necessarily all of them:

    printAA("Color Dictionary", dictionary, "=");

The output:

-- Color Dictionary --
blue=mavi, gray=gri, red=kırmızı

The following call specifies both of the parameters:

    printAA("Color Dictionary", dictionary, "=", "\n");

The output:

-- Color Dictionary --
blue=mavi
gray=gri
red=kırmızı

Default values can only be defined for the parameters that are at the end of the parameter list.

Special keywords as default arguments

The following special keywords act like compile-time literals having values corresponding to where they appear in code:

Although they can be useful anywhere in code, they work differently when used as default arguments. When they are used in regular code, their values refer to where they appear in code:

import std.stdio;

void func(int parameter) {
    writefln("Inside function %s at file %s, line %s.",
             __FUNCTION__, __FILE__, __LINE__);    // ← line 5
}

void main() {
    func(42);
}

The reported line 5 is inside the function:

Inside function deneme.func at file deneme.d, line 5.

However, sometimes it is more interesting to determine the line where a function is called from, not where the definition of the function is. When these special keywords are provided as default arguments, their values refer to where the function is called from:

import std.stdio;

void func(int parameter,
          string functionName = __FUNCTION__,
          string file = __FILE__,
          int line = __LINE__) {
    writefln("Called from function %s at file %s, line %s.",
             functionName, file, line);
}

void main() {
    func(42);    // ← line 12
}

This time the special keywords refer to main(), the caller of the function:

Called from function deneme.main at file deneme.d, line 12.

In addition to the above, there are also the following special tokens that take values depending on the compiler and the time of day:

Variadic functions

Despite appearances, default parameter values do not change the number of parameters that a function receives. For example, even though some parameters may be assigned their default values, printAA() always takes four parameters and uses them according to its implementation.

On the other hand, variadic functions can be called with unspecified number of arguments. We have already been taking advantage of this feature with functions like writeln(). writeln() can be called with any number of arguments:

    writeln(
        "hello", 7, "world", 9.8 /*, and any number of other
                                  *  arguments as needed */);

There are four ways of defining variadic functions in D:

The parameters of variadic functions are passed to the function as a slice. Variadic functions are defined with a single parameter of a specific type of slice followed immediately by the ... characters:

double sum(double[] numbers...) {
    double result = 0.0;

    foreach (number; numbers) {
        result += number;
    }

    return result;
}

That definition makes sum() a variadic function, meaning that it is able to receive any number of arguments as long as they are double or any other type that can implicitly be convertible to double:

    writeln(sum(1.1, 2.2, 3.3));

The single slice parameter and the ... characters represent all of the arguments. For example, the slice would have five elements if the function were called with five double values.

In fact, the variable number of parameters can also be passed as a single slice:

    writeln(sum([ 1.1, 2.2, 3.3 ]));    // same as above

Variadic functions can also have required parameters, which must be defined first in the parameter list. For example, the following function prints an unspecified number of parameters within parentheses. Although the function leaves the number of the elements flexible, it requires that the parentheses are always specified:

char[] parenthesize(
    string opening,  // ← The first two parameters must be
    string closing,  //   specified when the function is called
    string[] words...) {  // ← Need not be specified
    char[] result;

    foreach (word; words) {
        result ~= opening;
        result ~= word;
        result ~= closing;
    }

    return result;
}

The first two parameters are mandatory:

    parenthesize("{");     // ← compilation ERROR

As long as the mandatory parameters are specified, the rest are optional:

    writeln(parenthesize("{", "}", "apple", "pear", "banana"));

The output:

{apple}{pear}{banana}
Variadic function arguments have a short lifetime

The slice argument that is automatically generated for a variadic parameter points at a temporary array that has a short lifetime. This fact does not matter if the function uses the arguments only during its execution. However, it would be a bug if the function kept a slice to those elements for later use:

int[] numbersForLaterUse;

void foo(int[] numbers...) {
    numbersForLaterUse = numbers;    // ← BUG
}

struct S {
    string[] namesForLaterUse;

    void foo(string[] names...) {
        namesForLaterUse = names;    // ← BUG
    }
}

void bar() {
    foo(1, 10, 100);  /* The temporary array [ 1, 10, 100 ] is
                       * not valid beyond this point. */

    auto s = S();
    s.foo("hello", "world");  /* The temporary array
                               * [ "hello", "world" ] is not
                               * valid beyond this point. */

    // ...
}

void main() {
    bar();
}

Both the free-standing function foo() and the member function S.foo() are in error because they store slices to automatically-generated temporary arrays that live on the program stack. Those arrays are valid only during the execution of the variadic functions.

For that reason, if a function needs to store a slice to the elements of a variadic parameter, it must first take a copy of those elements:

void foo(int[] numbers...) {
    numbersForLaterUse = numbers.dup;    // ← correct
}

// ...

    void foo(string[] names...) {
        namesForLaterUse = names.dup;    // ← correct
    }

However, since variadic functions can also be called with slices of proper arrays, copying the elements would be unnecessary in those cases.

A solution that is both correct and efficient is to define two functions having the same name, one taking a variadic parameter and the other taking a proper slice. If the caller passes variable number of arguments, then the variadic version of the function is called; and if the caller passes a proper slice, then the version that takes a proper slice is called:

int[] numbersForLaterUse;

void foo(int[] numbers...) {
    /* Since this is the variadic version of foo(), we must
     * first take a copy of the elements before storing a
     * slice to them. */
    numbersForLaterUse = numbers.dup;
}

void foo(int[] numbers) {
    /* Since this is the non-variadic version of foo(), we can
     * store the slice as is. */
    numbersForLaterUse = numbers;
}

struct S {
    string[] namesForLaterUse;

    void foo(string[] names...) {
        /* Since this is the variadic version of S.foo(), we
         * must first take a copy of the elements before
         * storing a slice to them. */
        namesForLaterUse = names.dup;
    }

    void foo(string[] names) {
        /* Since this is the non-variadic version of S.foo(),
         * we can store the slice as is. */
        namesForLaterUse = names;
    }
}

void bar() {
    // This call is dispatched to the variadic function.
    foo(1, 10, 100);

    // This call is dispatched to the proper slice function.
    foo([ 2, 20, 200 ]);

    auto s = S();

    // This call is dispatched to the variadic function.
    s.foo("hello", "world");

    // This call is dispatched to the proper slice function.
    s.foo([ "hi", "moon" ]);

    // ...
}

void main() {
    bar();
}

Defining multiple functions with the same name but with different parameters is called function overloading, which is the subject of the next chapter.

Exercise

Assume that the following enum is already defined:

enum Operation { add, subtract, multiply, divide }

Also assume that there is a struct that represents the calculation of an operation and its two operands:

struct Calculation {
    Operation op;
    double first;
    double second;
}

For example, the object Calculation(Operation.divide, 7.7, 8.8) would represent the division of 7.7 by 8.8.

Design a function that receives an unspecified number of these struct objects, calculates the result of each Calculation, and then returns all of the results as a slice of type double[].

For example, it should be possible to call the function as in the following code:

void main() {
    writeln(
        calculate(Calculation(Operation.add, 1.1, 2.2),
                  Calculation(Operation.subtract, 3.3, 4.4),
                  Calculation(Operation.multiply, 5.5, 6.6),
                  Calculation(Operation.divide, 7.7, 8.8)));
}

The output of the code should be similar to the following:

[3.3, -1.1, 36.3, 0.875]