Section 6.3

An array parameter

The array type written out, and the absence of a variadic symbol — a lone value wraps itself.

A method can take a whole array. All it needs is the type written out.

@entry(start)
object MyProgram {
    start() {
        Console.print(text: $"total: {self.sum(values: [12, 19, 7])}");
        Console.print(text: $"total: {self.sum(values: 5)}");
    }

    sum(values: [int]) -> int {
        var total := 0;

        for value in values {
            total := total + value;
        }

        return total;
    }
}

[int] is a type

sum(values: [int]) -> int {

Brackets around a type rather than around values form the array type. [int] reads “array of integers”; [str] would be an array of texts. It is the type the compiler was already inferring on its own back in 4.3 when you wrote var temperatures := [12, 19, 7] — it simply has a name now that it has to be written.

The body of sum does nothing new: a for … in from 4.3, a running total, a return from 5.1. What is new is that the method works on values it did not write itself.

A lone value wraps itself

Look at the second call:

self.sum(values: 5);

5 is not an array, and yet the call goes through — it returns 5. A parameter typed [int] accepts a plain value directly, which the compiler wraps into a one-element array.

This is Archon’s answer to what other languages write with an ellipsis or a dedicated keyword: there is no variadic symbol in this language. An array parameter is enough, and the one-element case passes without ceremony.

The brackets stay compulsory as soon as there is more than one element. The wrapping is a convenience for the lone value only; two values call for the array written out, [12, 19], or the second one has nowhere to go.

Your turn

  • Pass values: [5] to the second call: the same result, written explicitly. That is what the wrapping builds for you.
  • Pass an empty array, values: []. The sum returns 0 — the loop takes no turn at all, and total leaves as it came in.
  • Write maximum(values: [int]) -> int returning the largest of the values. A hint: the method in 5.1 was already called maximum, but this one takes a single argument.
  • Add a second parameter to sum, with a default value, that is added to the total.