A Tour of Morfa

Overloading builtin operators

Existing operators, such as +, may be overloaded for new types simply by defining a new function with an appropriate name. For example, we may define a function + for adding arrays of ints of equal length element-wise:

import morfa.util.Range;

func + (a: int[], b: int[]): int[]
    assert (a.length == b.length);

    var result = new int[a.length];

    for (i in range(a.length))
        result[i] = a[i] + b[i];

    return result;

    var a: int[] = [1,2,3];
    var b: int[] = [4,5,6];
    var c = a + b;

    assert(c == [5,7,9]);