Programming Search⌘K

Taskcore

Overload an operator

Also called overload plus, define operator plus, implement __add__, implement the Add trait, operator+ for a class, vector addition operator.

Give a Vec2 type the operators + and == where the language allows user operators, and add and equals methods where it does not, then sum a list of vectors with them.

Task

Write a type Vec2, a vector in two dimensions with integer coordinates x and y. Give it addition, which adds the coordinates, and equality, which compares them. Where the language lets a type define operators, use + and ==, so that Vec2(1, 2) + Vec2(3, 4) == Vec2(4, 6) is true. Where it does not, give the type methods with the same meaning, such as add and equals.

Then use the operator. The function vector_sum(xs, ys) makes the vector Vec2(xs[i], ys[i]) for each index, adds all of them to the zero vector with +, and returns the coordinates of the sum as [x, y]. For example, vector_sum([1, 3], [2, 4]) is [4, 6]. The lists have 0 to 10,000 items, each coordinate has an absolute value of 10^9 or less, and the tests also check + and == directly.

Solutions

Language + == User operators
Python __add__ __eq__ and __hash__ yes, through special methods
JavaScript an add method an equals method no
TypeScript as JavaScript as JavaScript no
Java a plus method equals, generated by a record no
C# static Vec2 operator +(Vec2 a, Vec2 b) generated by a record struct yes
Go an Add method built in for structs with comparable fields no
Rust impl Add for Vec2 #[derive(PartialEq, Eq)] yes, through traits
C a function vec2_add a function vec2_equal no
C++ operator+= as a member and operator+ as a non-member operator== with = default yes
  • Python calls special methods for the operators: "to evaluate the expression x + y, where x is an instance of a class that has an add() method, type(x).add(x, y) is called".1 __add__ returns NotImplemented for an operand of another type, and Python then tries the other operand and at last raises TypeError. vector_sum passes the zero vector as the start value of sum, which then applies + to each item.
  • C# declares operators with the operator keyword. A binary operator "has two input parameters", and "at least one parameter must have type T or T? where T is the type that contains the operator declaration".2 A record struct writes equality for the type, including "Overrides of operator == and operator !=".3
  • Rust maps each operator to a trait in std::ops: "the addition operator (+) can be overloaded through the Add trait".4 Add has an associated type Output, the type of the result. #[derive(PartialEq, Eq)] gives == and !=, and an impl Sum lets Iterator::sum add the vectors.
  • C++ defines += as a member and + as a non-member function that uses it. cppreference gives the reason for the non-member: "Binary operators are typically implemented as non-members to maintain symmetry".5 A defaulted operator== compares the members. For !=, "overload resolution also considers the rewritten candidates operator==", so a != b works without a second operator.5
  • Go has no user operators. Its FAQ says: "Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it."6 The type has an Add method. == works without code, because the fields are comparable, and a Vec2 can be a map key.
  • Java has no user operators either. The specification allows + only for strings and numbers: "the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs".7 The record has a plus method, and it generates equals and hashCode from the two components.
  • JavaScript and TypeScript have no user operators. The + operator converts an object to a primitive with Symbol.toPrimitive, "before falling back to using the object's valueOf() and toString() methods", so a + b on two vectors gives a string.8 The class has add and equals.
  • C has functions in place of operators. vec2_add returns a new struct, and vec2_equal compares the fields.

Alternatives

  • A mutating method. v.add_in_place(w) changes v and makes no new object, which is faster in a hot loop. It is the role of +=; keep + free of side effects.
  • A free function. In Go, C and Java, Add(v, w) as a function in place of a method treats both operands the same way, like the C++ non-member operator+.
  • The operator of a generic interface. Rust's Add<Rhs = Self> lets the right operand have another type, such as a Vec2 + i64. Rhs "is Self by default, but this is not mandatory".9 Define such mixed operators only when the meaning is clear to a reader.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: no vectors give the zero vector, [0, 0]. The sum must start from the zero vector, not from the first item.
  • single: one vector is its own sum.
  • negative: negative coordinates add as numbers.
  • cancel: two opposite vectors give the zero vector.
  • limit: three coordinates of 10^9 give 3 × 10^9, which is more than a 32-bit int holds. The solutions use 64-bit integers; JavaScript numbers hold it exactly.

Pitfalls

  • sum without a start value. Python's sum starts from 0, so the first step is 0 + Vec2(...), and int does not know Vec2:
class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        if not isinstance(other, Vec2):
            return NotImplemented
        return Vec2(self.x + other.x, self.y + other.y)


vectors = [Vec2(1, 2), Vec2(3, 4)]
try:
    sum(vectors)
except TypeError as e:
    print("TypeError:", e)
total = sum(vectors, Vec2(0, 0))
print(total.x, total.y)
Output
TypeError: unsupported operand type(s) for +: 'int' and 'Vec2'
4 6

Pass the zero vector as the start value, or define __radd__ to accept 0.

  • == that compares references. In Java, == on two objects does not call equals: "If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality."7 This is true for records too, so use equals. In C#, a class that defines operator == must also define !=; the operators "Must be overloaded in pairs".2
  • An operator with a surprising meaning. A reader expects + on vectors to add the coordinates. An operator that changes an operand, that is not symmetric, or that does work unrelated to its usual meaning makes code hard to read.
  • Raising an error in place of NotImplemented. In Python, __add__ that raises TypeError for another type stops Python from trying the other operand's __radd__. Numeric methods "should return this value if they do not implement the operation for the operands provided".1
  • Overflow. + on 32-bit coordinates overflows for large values. Choose a type that holds the largest sum.

Code

The build runs the native tests of each language in a pinned toolchain.

vec2.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/overload-an-operator/.

"""A 2D vector with the operators + and ==."""


class Vec2:
    __slots__ = ("_x", "_y")

    def __init__(self, x: int, y: int) -> None:
        self._x, self._y = x, y

    @property
    def x(self) -> int:
        return self._x

    @property
    def y(self) -> int:
        return self._y

    def __add__(self, other: object) -> "Vec2":
        if not isinstance(other, Vec2):
            return NotImplemented
        return Vec2(self._x + other._x, self._y + other._y)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Vec2):
            return NotImplemented
        return self._x == other._x and self._y == other._y

    def __hash__(self) -> int:
        return hash((self._x, self._y))

    def __repr__(self) -> str:
        return f"Vec2({self._x}, {self._y})"


def vector_sum(xs: list[int], ys: list[int]) -> list[int]:
    if len(xs) != len(ys):
        raise ValueError("the lists must have the same length")
    # sum() starts from the zero vector and applies + to each item.
    total = sum((Vec2(x, y) for x, y in zip(xs, ys)), Vec2(0, 0))
    return [total.x, total.y]
test_vec2.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/overload-an-operator/.

import pytest

from vec2 import Vec2, vector_sum

CASES = {
    "two": (([1, 3], [2, 4]), [4, 6]),
    "three": (([1, 2, 3], [10, 20, 30]), [6, 60]),
    "empty": (([], []), [0, 0]),
    "single": (([5], [-7]), [5, -7]),
    "negative": (([-1, -2], [-3, -4]), [-3, -7]),
    "cancel": (([3, -3], [5, -5]), [0, 0]),
    "limit": (([10**9] * 3, [-(10**9)] * 3), [3 * 10**9, -3 * 10**9]),
}


@pytest.mark.parametrize("name", CASES)
def test_vector_sum(name):
    args, want = CASES[name]
    assert vector_sum(*args) == want


def test_operators():
    a, b = Vec2(1, 2), Vec2(3, 4)
    assert a + b == Vec2(4, 6)
    assert a != b and a == Vec2(1, 2)
    assert hash(a) == hash(Vec2(1, 2))
    with pytest.raises(TypeError):
        a + 3
vec2.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#include "vec2.hpp"

#include <stdexcept>

namespace vec2 {

Vec2 vector_sum(const std::vector<std::int64_t>& xs, const std::vector<std::int64_t>& ys) {
    if (xs.size() != ys.size()) {
        throw std::invalid_argument("the lists must have the same length");
    }
    Vec2 total;
    for (std::size_t i = 0; i < xs.size(); i++) {
        total = total + Vec2{xs[i], ys[i]};
    }
    return total;
}

}  // namespace vec2
vec2.hpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#ifndef VEC2_HPP
#define VEC2_HPP

#include <cstdint>
#include <vector>

namespace vec2 {

struct Vec2 {
    std::int64_t x = 0;
    std::int64_t y = 0;

    // The compound operator is a member; operator+ below is built on it.
    Vec2& operator+=(const Vec2& other) {
        x += other.x;
        y += other.y;
        return *this;
    }

    // The compiler writes == from the members, and != from ==.
    friend bool operator==(const Vec2&, const Vec2&) = default;
};

// A non-member, so that both operands are treated the same way.
inline Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; }

// Returns the sum of the vectors (xs[i], ys[i]); throws std::invalid_argument when the lengths differ.
Vec2 vector_sum(const std::vector<std::int64_t>& xs, const std::vector<std::int64_t>& ys);

}  // namespace vec2

#endif
test_vec2.cpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#include "vec2.hpp"

#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>

using vec2::Vec2;

static int failures = 0;

static void check(std::string_view name, const std::vector<std::int64_t>& xs, const std::vector<std::int64_t>& ys,
                  Vec2 want) {
    if (vec2::vector_sum(xs, ys) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

static void expect(std::string_view name, bool ok) {
    if (!ok) {
        std::cerr << "check " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("two", {1, 3}, {2, 4}, {4, 6});
    check("three", {1, 2, 3}, {10, 20, 30}, {6, 60});
    check("empty", {}, {}, {0, 0});
    check("single", {5}, {-7}, {5, -7});
    check("negative", {-1, -2}, {-3, -4}, {-3, -7});
    check("cancel", {3, -3}, {5, -5}, {0, 0});
    check("limit", {1000000000, 1000000000, 1000000000}, {-1000000000, -1000000000, -1000000000},
          {3000000000, -3000000000});

    Vec2 a{1, 2}, b{3, 4};
    expect("add", a + b == Vec2{4, 6});
    expect("equal", a == Vec2{1, 2} && a != b);
    Vec2 c = a;
    c += b;
    expect("compound", c == Vec2{4, 6});

    if (failures == 0) {
        std::cout << "all tests passed\n";
    }
    return failures == 0 ? 0 : 1;
}
Vec2.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

import java.util.List;

/**
 * A 2D vector. Java has no user operators, so the type has a plus method in place of +, and the
 * record generates equals in place of ==.
 */
public record Vec2(long x, long y) {
  public static final Vec2 ZERO = new Vec2(0, 0);

  public Vec2 plus(Vec2 other) {
    return new Vec2(x + other.x, y + other.y);
  }

  public static List<Long> vectorSum(List<Long> xs, List<Long> ys) {
    if (xs.size() != ys.size()) {
      throw new IllegalArgumentException("the lists must have the same length");
    }
    Vec2 total = ZERO;
    for (int i = 0; i < xs.size(); i++) {
      total = total.plus(new Vec2(xs.get(i), ys.get(i)));
    }
    return List.of(total.x, total.y);
  }
}
Vec2Test.java 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class Vec2Test {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("two", List.of(1L, 3L), List.of(2L, 4L), List.of(4L, 6L)),
        Arguments.of("three", List.of(1L, 2L, 3L), List.of(10L, 20L, 30L), List.of(6L, 60L)),
        Arguments.of("empty", List.of(), List.of(), List.of(0L, 0L)),
        Arguments.of("single", List.of(5L), List.of(-7L), List.of(5L, -7L)),
        Arguments.of("negative", List.of(-1L, -2L), List.of(-3L, -4L), List.of(-3L, -7L)),
        Arguments.of("cancel", List.of(3L, -3L), List.of(5L, -5L), List.of(0L, 0L)),
        Arguments.of(
            "limit",
            List.of(1_000_000_000L, 1_000_000_000L, 1_000_000_000L),
            List.of(-1_000_000_000L, -1_000_000_000L, -1_000_000_000L),
            List.of(3_000_000_000L, -3_000_000_000L)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void vectorSum(String name, List<Long> xs, List<Long> ys, List<Long> want) {
    assertEquals(want, Vec2.vectorSum(xs, ys), name);
  }

  @Test
  void methodsInPlaceOfOperators() {
    Vec2 a = new Vec2(1, 2);
    Vec2 b = new Vec2(3, 4);
    assertEquals(new Vec2(4, 6), a.plus(b));
    assertNotEquals(a, b);
    Vec2 same = new Vec2(1, 2);
    assertEquals(a, same);
    assertNotSame(a, same);
  }
}
vec2.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#include "vec2.h"

Vec2 vec2_add(Vec2 a, Vec2 b) { return (Vec2){a.x + b.x, a.y + b.y}; }

bool vec2_equal(Vec2 a, Vec2 b) { return a.x == b.x && a.y == b.y; }

Vec2 vector_sum(const long long *xs, const long long *ys, size_t n) {
    Vec2 total = {0, 0};
    for (size_t i = 0; i < n; i++) {
        total = vec2_add(total, (Vec2){xs[i], ys[i]});
    }
    return total;
}
vec2.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#ifndef VEC2_H
#define VEC2_H

#include <stdbool.h>
#include <stddef.h>

// C has no user operators, so the type has functions in place of + and ==.
typedef struct {
    long long x, y;
} Vec2;

Vec2 vec2_add(Vec2 a, Vec2 b);
bool vec2_equal(Vec2 a, Vec2 b);

// vector_sum returns the sum of the vectors (xs[i], ys[i]).
Vec2 vector_sum(const long long *xs, const long long *ys, size_t n);

#endif
test_vec2.c 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

#include "vec2.h"

#include <stdio.h>

static int failures = 0;

static void check(const char *name, const long long *xs, const long long *ys, size_t n, long long wx, long long wy) {
    Vec2 got = vector_sum(xs, ys, n);
    if (got.x != wx || got.y != wy) {
        fprintf(stderr, "case %s failed: got (%lld, %lld), want (%lld, %lld)\n", name, got.x, got.y, wx, wy);
        failures++;
    }
}

static void expect(const char *name, bool ok) {
    if (!ok) {
        fprintf(stderr, "check %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("two", (long long[]){1, 3}, (long long[]){2, 4}, 2, 4, 6);
    check("three", (long long[]){1, 2, 3}, (long long[]){10, 20, 30}, 3, 6, 60);
    check("empty", NULL, NULL, 0, 0, 0);
    check("single", (long long[]){5}, (long long[]){-7}, 1, 5, -7);
    check("negative", (long long[]){-1, -2}, (long long[]){-3, -4}, 2, -3, -7);
    check("cancel", (long long[]){3, -3}, (long long[]){5, -5}, 2, 0, 0);
    check("limit", (long long[]){1000000000, 1000000000, 1000000000},
          (long long[]){-1000000000, -1000000000, -1000000000}, 3, 3000000000LL, -3000000000LL);

    Vec2 a = {1, 2}, b = {3, 4};
    expect("add", vec2_equal(vec2_add(a, b), (Vec2){4, 6}));
    expect("equal", vec2_equal(a, (Vec2){1, 2}) && !vec2_equal(a, b));

    if (failures == 0) {
        printf("all tests passed\n");
    }
    return failures == 0 ? 0 : 1;
}
Vec2.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

using System;
using System.Collections.Generic;

/// <summary>A 2D vector. The record struct generates == and !=; the type defines +.</summary>
public readonly record struct Vec2(long X, long Y)
{
    public static readonly Vec2 Zero = new(0, 0);

    public static Vec2 operator +(Vec2 a, Vec2 b) => new(a.X + b.X, a.Y + b.Y);

    public static long[] VectorSum(IReadOnlyList<long> xs, IReadOnlyList<long> ys)
    {
        if (xs.Count != ys.Count)
        {
            throw new ArgumentException("the lists must have the same length");
        }
        var total = Zero;
        for (var i = 0; i < xs.Count; i++)
        {
            total += new Vec2(xs[i], ys[i]);
        }
        return new[] { total.X, total.Y };
    }
}
Vec2Tests.cs 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

using Xunit;

public sealed class Vec2Tests
{
    public static TheoryData<string, long[], long[], long[]> Cases => new()
    {
        { "two", new long[] { 1, 3 }, new long[] { 2, 4 }, new long[] { 4, 6 } },
        { "three", new long[] { 1, 2, 3 }, new long[] { 10, 20, 30 }, new long[] { 6, 60 } },
        { "empty", new long[] { }, new long[] { }, new long[] { 0, 0 } },
        { "single", new long[] { 5 }, new long[] { -7 }, new long[] { 5, -7 } },
        { "negative", new long[] { -1, -2 }, new long[] { -3, -4 }, new long[] { -3, -7 } },
        { "cancel", new long[] { 3, -3 }, new long[] { 5, -5 }, new long[] { 0, 0 } },
        { "limit", new long[] { 1_000_000_000, 1_000_000_000, 1_000_000_000 },
          new long[] { -1_000_000_000, -1_000_000_000, -1_000_000_000 }, new long[] { 3_000_000_000, -3_000_000_000 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void VectorSum(string name, long[] xs, long[] ys, long[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Vec2.VectorSum(xs, ys));
    }

    [Fact]
    public void Operators()
    {
        var a = new Vec2(1, 2);
        var b = new Vec2(3, 4);
        Assert.True(a + b == new Vec2(4, 6));
        Assert.True(a != b);
        Assert.False(a == b);
        var c = a;
        c += b;
        Assert.Equal(new Vec2(4, 6), c);
    }
}
vec2.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

// JavaScript has no user operators, so the type has methods in place of + and ==.
export class Vec2 {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    Object.freeze(this);
  }

  add(other) {
    return new Vec2(this.x + other.x, this.y + other.y);
  }

  equals(other) {
    return other instanceof Vec2 && this.x === other.x && this.y === other.y;
  }
}

export function vectorSum(xs, ys) {
  if (xs.length !== ys.length) {
    throw new RangeError("the lists must have the same length");
  }
  const total = xs.reduce((acc, x, i) => acc.add(new Vec2(x, ys[i])), new Vec2(0, 0));
  return [total.x, total.y];
}
vec2.test.js 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { Vec2, vectorSum } from "./vec2.js";

const cases = [
  ["two", [[1, 3], [2, 4]], [4, 6]],
  ["three", [[1, 2, 3], [10, 20, 30]], [6, 60]],
  ["empty", [[], []], [0, 0]],
  ["single", [[5], [-7]], [5, -7]],
  ["negative", [[-1, -2], [-3, -4]], [-3, -7]],
  ["cancel", [[3, -3], [5, -5]], [0, 0]],
  ["limit", [[1e9, 1e9, 1e9], [-1e9, -1e9, -1e9]], [3e9, -3e9]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(vectorSum(...args), want);
  });
}

test("methods in place of operators", () => {
  const a = new Vec2(1, 2);
  const b = new Vec2(3, 4);
  assert.ok(a.add(b).equals(new Vec2(4, 6)));
  assert.ok(!a.equals(b) && a.equals(new Vec2(1, 2)));
  // == and === compare references, so two equal vectors are not ===.
  assert.ok(a !== new Vec2(1, 2));
  // + converts both objects to strings.
  assert.equal(a + b, "[object Object][object Object]");
});
vec2.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

// JavaScript has no user operators, so the type has methods in place of + and ==.
export class Vec2 {
  readonly x: number;
  readonly y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
    Object.freeze(this);
  }

  add(other: Vec2): Vec2 {
    return new Vec2(this.x + other.x, this.y + other.y);
  }

  equals(other: unknown): boolean {
    return other instanceof Vec2 && this.x === other.x && this.y === other.y;
  }
}

export function vectorSum(xs: number[], ys: number[]): number[] {
  if (xs.length !== ys.length) {
    throw new RangeError("the lists must have the same length");
  }
  const total = xs.reduce((acc, x, i) => acc.add(new Vec2(x, ys[i])), new Vec2(0, 0));
  return [total.x, total.y];
}
vec2.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { Vec2, vectorSum } from "./vec2.ts";

const cases: [string, [number[], number[]], number[]][] = [
  ["two", [[1, 3], [2, 4]], [4, 6]],
  ["three", [[1, 2, 3], [10, 20, 30]], [6, 60]],
  ["empty", [[], []], [0, 0]],
  ["single", [[5], [-7]], [5, -7]],
  ["negative", [[-1, -2], [-3, -4]], [-3, -7]],
  ["cancel", [[3, -3], [5, -5]], [0, 0]],
  ["limit", [[1e9, 1e9, 1e9], [-1e9, -1e9, -1e9]], [3e9, -3e9]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(vectorSum(args[0], args[1]), want);
  });
}

test("methods in place of operators", () => {
  const a = new Vec2(1, 2);
  const b = new Vec2(3, 4);
  assert.ok(a.add(b).equals(new Vec2(4, 6)));
  assert.ok(!a.equals(b) && a.equals(new Vec2(1, 2)));
  // == and === compare references, so two equal vectors are not ===.
  assert.ok(a !== new Vec2(1, 2));
  // + converts both objects to strings.
  assert.equal(`${a}${b}`, "[object Object][object Object]");
});
vec2.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

// Package vec2 gives a 2D vector. Go has no user operators, so the type has
// an Add method; == works on the struct because its fields are comparable.
package vec2

import "fmt"

// Vec2 is a 2D vector with integer coordinates.
type Vec2 struct {
	X, Y int64
}

// Add returns the sum of v and w.
func (v Vec2) Add(w Vec2) Vec2 {
	return Vec2{v.X + w.X, v.Y + w.Y}
}

// VectorSum returns the sum of the vectors (xs[i], ys[i]) as [x, y].
func VectorSum(xs, ys []int64) ([]int64, error) {
	if len(xs) != len(ys) {
		return nil, fmt.Errorf("the lists must have the same length")
	}
	var total Vec2 // the zero value is the zero vector
	for i := range xs {
		total = total.Add(Vec2{xs[i], ys[i]})
	}
	return []int64{total.X, total.Y}, nil
}
vec2_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

package vec2

import (
	"slices"
	"testing"
)

var cases = []struct {
	name   string
	xs, ys []int64
	want   []int64
}{
	{"two", []int64{1, 3}, []int64{2, 4}, []int64{4, 6}},
	{"three", []int64{1, 2, 3}, []int64{10, 20, 30}, []int64{6, 60}},
	{"empty", []int64{}, []int64{}, []int64{0, 0}},
	{"single", []int64{5}, []int64{-7}, []int64{5, -7}},
	{"negative", []int64{-1, -2}, []int64{-3, -4}, []int64{-3, -7}},
	{"cancel", []int64{3, -3}, []int64{5, -5}, []int64{0, 0}},
	{"limit", []int64{1e9, 1e9, 1e9}, []int64{-1e9, -1e9, -1e9}, []int64{3e9, -3e9}},
}

func TestVectorSum(t *testing.T) {
	for _, c := range cases {
		got, err := VectorSum(c.xs, c.ys)
		if err != nil || !slices.Equal(got, c.want) {
			t.Errorf("case %s: got %v, %v; want %v", c.name, got, err, c.want)
		}
	}
}

func TestOperators(t *testing.T) {
	a, b := Vec2{1, 2}, Vec2{3, 4}
	if a.Add(b) != (Vec2{4, 6}) || a == b || a != (Vec2{1, 2}) {
		t.Error("Add or == gave a wrong result")
	}
	seen := map[Vec2]bool{a: true}
	if !seen[Vec2{1, 2}] {
		t.Error("an equal vector is not the same map key")
	}
}
vec2.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

//! A 2D vector with `+` from the `Add` trait and `==` from a derived `PartialEq`.

use std::iter::Sum;
use std::ops::{Add, AddAssign};

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Vec2 {
    pub x: i64,
    pub y: i64,
}

impl Vec2 {
    pub fn new(x: i64, y: i64) -> Self {
        Vec2 { x, y }
    }
}

impl Add for Vec2 {
    type Output = Vec2;

    fn add(self, other: Vec2) -> Vec2 {
        Vec2::new(self.x + other.x, self.y + other.y)
    }
}

impl AddAssign for Vec2 {
    fn add_assign(&mut self, other: Vec2) {
        *self = *self + other;
    }
}

/// Lets `Iterator::sum` add vectors, starting from the zero vector.
impl Sum for Vec2 {
    fn sum<I: Iterator<Item = Vec2>>(iter: I) -> Vec2 {
        iter.fold(Vec2::default(), |a, b| a + b)
    }
}

/// Returns the sum of the vectors (xs[i], ys[i]) as [x, y], or None when the lengths differ.
pub fn vector_sum(xs: &[i64], ys: &[i64]) -> Option<[i64; 2]> {
    if xs.len() != ys.len() {
        return None;
    }
    let total: Vec2 = xs.iter().zip(ys).map(|(&x, &y)| Vec2::new(x, y)).sum();
    Some([total.x, total.y])
}
tests/vec2_test.rs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/overload-an-operator/.

use algo_overload_an_operator::{vector_sum, Vec2};

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<i64>, Vec<i64>, [i64; 2])> = vec![
        ("two", vec![1, 3], vec![2, 4], [4, 6]),
        ("three", vec![1, 2, 3], vec![10, 20, 30], [6, 60]),
        ("empty", vec![], vec![], [0, 0]),
        ("single", vec![5], vec![-7], [5, -7]),
        ("negative", vec![-1, -2], vec![-3, -4], [-3, -7]),
        ("cancel", vec![3, -3], vec![5, -5], [0, 0]),
        ("limit", vec![1_000_000_000; 3], vec![-1_000_000_000; 3], [3_000_000_000, -3_000_000_000]),
    ];
    for (name, xs, ys, want) in cases {
        assert_eq!(vector_sum(&xs, &ys), Some(want), "case {name}");
    }
}

#[test]
fn operators() {
    let a = Vec2::new(1, 2);
    let b = Vec2::new(3, 4);
    assert_eq!(a + b, Vec2::new(4, 6));
    assert!(a != b && a == Vec2::new(1, 2));
    let mut c = a;
    c += b;
    assert_eq!(c, Vec2::new(4, 6));
    assert_eq!(vector_sum(&[1], &[]), None);
}

References

  1. Data model, The Python Language Reference, 3.3.8 Emulating numeric types; NotImplemented
  2. Operator overloading, C# reference, Introduction; Overloadable operators
  3. Records, C# reference, Value equality
  4. std::ops, Rust standard library, Description
  5. Operator overloading, cppreference.com, Restrictions; Binary arithmetic operators
  6. Frequently Asked Questions, The Go Programming Language, Why does Go not support overloading of methods and operators?
  7. Chapter 15: Expressions, The Java Language Specification, Java SE 21, 15.18 Additive Operators
  8. Symbol.toPrimitive, JavaScript reference, MDN, Description
  9. Add trait, Rust standard library, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source