Taskcore
Implement equality for a type
Also called implement equals, override equals, value equality for a class, define equality, __eq__, IEquatable, PartialEq, operator==, equals and hashCode.
Give a Money class with an amount and a currency value equality and a hash that agrees with it, so that equal values are equal from both sides and a hash set keeps only one of them.
- Evidence
- Code in 9 languages
Task
Write a class Money with two fields: an amount in cents, and a currency code of 3 letters. Two Money values are equal when their amounts are equal and their currency codes are equal; "eur" and "EUR" are the same currency. Give the class an equality that follows this rule, and a hash code that agrees with it, so that a Money value works as a key of a hash map and as an item of a hash set.
Then use it. The function count_distinct(amounts, currencies) makes the value Money(amounts[i], currencies[i]) for each index, puts the values in a hash set and returns the number of different values. For example, count_distinct([500, 500, 500, 700], ["EUR", "USD", "EUR", "EUR"]) is 3. The lists have 0 to 10,000 items, each amount has an absolute value of 10^12 or less, and the tests also check the rules of equality directly.
The rules come from Java's Object.equals, which says that equality "implements an equivalence relation on non-null object references".1 It must be reflexive, symmetric and transitive, and Java adds: "For any non-null reference value x, x.equals(null) should return false." The hash code must agree: "If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result."
Solutions
| Language | Equality | Hash | == on two objects |
|---|---|---|---|
| Python | __eq__ |
__hash__ |
calls __eq__ |
| JavaScript | an equals method by convention |
a string key() for Set and Map |
identity, cannot change |
| TypeScript | as JavaScript, equals(other: unknown) |
as JavaScript | identity, cannot change |
| Java | override equals(Object) |
override hashCode() |
identity, cannot change |
| C# | IEquatable<Money>.Equals and an override of Equals(object) |
override GetHashCode() |
calls Equals after the class defines operator == |
| Go | built-in == on a struct with comparable fields; an Equal method |
built in for map keys | compares the fields |
| Rust | #[derive(PartialEq, Eq)] |
#[derive(Hash)] |
calls PartialEq::eq |
| C | a function money_equal |
a function money_hash |
not defined for structs |
| C++ | operator== with = default |
a specialization of std::hash |
calls operator== |
- Normalize in the constructor. Each solution converts the currency code to upper case when it makes the value. Equality and the hash can then compare the fields directly, and they cannot disagree about the case.
- Python returns
NotImplementedwhen the other operand is not aMoney, and Python then tries the other operand's method and at last identity.__hash__hashes a tuple of the same two fields; the data model advises "packing them into a tuple and hashing the tuple".2 The fields are read-only properties, because a hash of a field that changes breaks a set. - Java checks for the same object first, then uses
instanceofwith a pattern, which also returns false fornull.Objects.hash(cents, currency)uses the same fields asequals. The class isfinal, so no subclass can add a field toequalsand break symmetry. - C# implements
IEquatable<Money>, which gives a typedEquals, and the override ofEquals(object)calls it. A class must also define==and!=, because "A plain class uses reference equality, so == and Equals test whether two variables point to the same object."3HashCode.Combinemixes the fields. - Go needs no method for equality. The spec says that "Struct types are comparable if all their field types are comparable. Two struct values are equal if their corresponding non-blank field values are equal."4 A comparable struct can be a map key, so a
map[Money]struct{}is the hash set. The fields are not exported, so other packages must use the constructorNew, which makes the code upper case. - Rust derives
PartialEq,EqandHashfrom the two fields.Eqadds the promise that the value is equal to itself, and "This property cannot be checked by the compiler, and therefore Eq is a trait without methods."5 TheHashdocumentation gives the rule that the derive keeps: "k1 == k2 -> hash(k1) == hash(k2)".6 - C++ defaults
operator==, which compares the members in the order of their declaration, and C++20 rewritesa != bas!(a == b). The default order of the members is "The non-static data members of C, in declaration order".7std::unordered_setneeds a specialization ofstd::hashthat uses the same members. - C has no operators for structs.
money_equalcompares the fields, andmoney_hashis an FNV-1a hash of the same fields.count_distinctuses a small hash set with open addressing. - JavaScript and TypeScript cannot change equality. MDN says that for two distinct objects with the same structure, all the equality operators "will evaluate to false".8 The class has an
equalsmethod for code that calls it, and akey()that turns the value into a string, because aSetof strings compares them by value.
Alternatives
- Generate the methods. A Java or C#
record, a Kotlindata class, a Python@dataclass(frozen=True)and Rust's#[derive]write equality and the hash from the fields. Use them when the default rule, which compares all the fields, is the right rule. Here the currency must be normalized first, which a record does in its constructor. The C# guide says: "Choose record types for implementing value equality, and the compiler generates all the necessary equality members for you."3 - Compare with
getClass(). In Java,getClass() != o.getClass()in place ofinstanceofmakes an object equal only to objects of the same class, which keeps symmetry when a subclass adds a field. A subclass that adds no field is then never equal to its base class, though. - A typed equality method only. In JavaScript and in C, a function
equals(a, b)is enough when no hash set needs the values.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no values give a count of 0.case:gbp,GBPandGbpare the same currency. Without the normalization, the count is 3.other-currency: three values with the amount 0 in different currencies are different, so the hash and the equality must both use the currency.negative: -5 and 5 are different amounts.limit: amounts of 10^12 need a 64-bit integer; a 32-bitintoverflows. JavaScript numbers hold them exactly, because they are smaller than 2^53.
Pitfalls
- A hash that disagrees with equality. If
equalsnormalizes the currency andhashCodehashes the raw string, two equal values can go to different buckets, and the set keeps both. Normalize once, in the constructor, and use the same fields in both methods. - Equality across a class hierarchy. If a subclass adds a field to
equalsand checks for its own type, a base object can be equal to a subclass object, but not the other way round:
public class Main {
static class Point {
final int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}
static class ColorPoint extends Point {
final String color;
ColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}
@Override
public boolean equals(Object o) {
return o instanceof ColorPoint cp && super.equals(cp) && color.equals(cp.color);
}
}
public static void main(String[] args) {
Point p = new Point(1, 2);
ColorPoint red = new ColorPoint(1, 2, "red");
System.out.println(p.equals(red) + " " + red.equals(p));
}
}
true false
p.equals(red) is true but red.equals(p) is false, so equality is not symmetric, and a collection can give different answers for the same two objects. Make the class final, or give ColorPoint a Point field in place of the subclass.
- An overload in place of an override. In Java,
public boolean equals(Money other)does not overrideequals(Object), soHashSetstill uses identity. In C#, the same mistake leavesEquals(object)unchanged. Use@Overrideandoverride, which make the compiler check the signature. ==that stays identity. In Java and JavaScript,a == banda === bcompare references even after the class hasequals. In C#, a class that overridesEqualsand notoperator ==givestruefora.Equals(b)andfalsefora == b.memcmpon structs in C. The compiler can add padding bytes between the fields, and their values are not defined, so two equal structs can have different bytes. Compare the fields one by one.- Mutable fields. A value whose fields change after it goes into a hash set is in the wrong bucket. Python says that if a class "defines mutable objects and implements an eq() method, it should not implement hash()".2 The solutions make the fields read-only.
Related tasks
- Define a method on a type defines a value type with methods; its record gets equality from the language.
- Implement ordering for a type adds an order that must be consistent with this equality.
- Define a record type gets equality, the hash and the string form from a record or a data class.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-equality-for-a-type/.
class Money:
"""An amount in cents and a currency code. Equal amounts in the same currency are equal."""
__slots__ = ("_cents", "_currency")
def __init__(self, cents, currency):
self._cents = cents
self._currency = currency.upper() # "eur" and "EUR" are the same currency
@property
def cents(self):
return self._cents
@property
def currency(self):
return self._currency
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented # Python then tries other.__eq__, and at last identity
return self._cents == other._cents and self._currency == other._currency
def __hash__(self):
# The same fields as __eq__, so equal values have equal hashes.
return hash((self._cents, self._currency))
def __repr__(self):
return f"Money({self._cents!r}, {self._currency!r})"
def count_distinct(amounts, currencies):
return len({Money(a, c) for a, c in zip(amounts, currencies)})
test_money.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-equality-for-a-type/.
import pytest
from money import Money, count_distinct
CASES = {
"two-equal": (([1250, 1250], ["EUR", "EUR"]), 1),
"different-amounts": (([100, 200, 100], ["USD", "USD", "USD"]), 2),
"mixed": (([500, 500, 500, 700], ["EUR", "USD", "EUR", "EUR"]), 3),
"empty": (([], []), 0),
"case": (([999, 999, 999], ["gbp", "GBP", "Gbp"]), 1),
"other-currency": (([0, 0, 0], ["EUR", "USD", "JPY"]), 3),
"negative": (([-5, 5, -5], ["EUR", "EUR", "EUR"]), 2),
"limit": (([10**12, -(10**12), 10**12], ["usd", "USD", "USD"]), 2),
}
@pytest.mark.parametrize("name", CASES)
def test_count_distinct(name):
args, want = CASES[name]
assert count_distinct(*args) == want
def test_equality_rules():
a, b, c = Money(1250, "EUR"), Money(1250, "eur"), Money(1250, "EUR")
assert a == a
assert a == b and b == a
assert a == b and b == c and a == c
assert a != Money(1251, "EUR")
assert a != Money(1250, "USD")
assert hash(a) == hash(b)
def test_other_types_are_not_equal():
assert Money(1, "EUR") != 1
assert Money(1, "EUR") != (1, "EUR")
assert Money(1, "EUR") is not None
def test_dict_key():
names = {Money(500, "USD"): "lunch"}
assert names[Money(500, "usd")] == "lunch"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#include "money.hpp"
#include <cctype>
#include <unordered_set>
namespace money {
Money::Money(std::int64_t cents, std::string_view currency) : cents_(cents), currency_(currency) {
for (char& c : currency_) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c))); // "eur" and "EUR" are the same currency
}
}
int count_distinct(const std::vector<std::int64_t>& amounts, const std::vector<std::string>& currencies) {
std::unordered_set<Money> seen;
for (std::size_t i = 0; i < amounts.size(); i++) {
seen.emplace(amounts[i], currencies[i]);
}
return static_cast<int>(seen.size());
}
} // namespace money
money.hpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#ifndef MONEY_HPP
#define MONEY_HPP
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <vector>
namespace money {
// An amount in cents and an upper-case currency code.
class Money {
public:
Money(std::int64_t cents, std::string_view currency);
std::int64_t cents() const { return cents_; }
const std::string& currency() const { return currency_; }
// Compares the members in order; != comes from == (C++20).
bool operator==(const Money&) const = default;
private:
std::int64_t cents_;
std::string currency_;
};
int count_distinct(const std::vector<std::int64_t>& amounts, const std::vector<std::string>& currencies);
} // namespace money
// std::unordered_set needs a hash; it uses the same members as operator==.
template <>
struct std::hash<money::Money> {
std::size_t operator()(const money::Money& m) const noexcept {
std::size_t h = std::hash<std::string>{}(m.currency());
return h ^ (std::hash<std::int64_t>{}(m.cents()) + 0x9e3779b9 + (h << 6) + (h >> 2));
}
};
#endif
test_money.cpp 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#include "money.hpp"
#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::int64_t>& amounts,
const std::vector<std::string>& currencies, int want) {
if (money::count_distinct(amounts, currencies) != 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-equal", {1250, 1250}, {"EUR", "EUR"}, 1);
check("different-amounts", {100, 200, 100}, {"USD", "USD", "USD"}, 2);
check("mixed", {500, 500, 500, 700}, {"EUR", "USD", "EUR", "EUR"}, 3);
check("empty", {}, {}, 0);
check("case", {999, 999, 999}, {"gbp", "GBP", "Gbp"}, 1);
check("other-currency", {0, 0, 0}, {"EUR", "USD", "JPY"}, 3);
check("negative", {-5, 5, -5}, {"EUR", "EUR", "EUR"}, 2);
check("limit", {1000000000000, -1000000000000, 1000000000000}, {"usd", "USD", "USD"}, 2);
money::Money a{1250, "EUR"}, b{1250, "eur"};
expect("reflexive", a == a);
expect("symmetric", a == b && b == a);
expect("not equal", !(a != b));
expect("hash", std::hash<money::Money>{}(a) == std::hash<money::Money>{}(b));
expect("other amount", a != money::Money(1251, "EUR"));
expect("other currency", a != money::Money(1250, "USD"));
std::unordered_map<money::Money, std::string> names{{money::Money(500, "USD"), "lunch"}};
expect("map key", names.at(money::Money(500, "usd")) == "lunch");
if (failures == 0) {
std::cout << "all cases passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
/** An amount in cents and a currency code. The class is final, so no subclass can break equals. */
public final class Money {
private final long cents;
private final String currency;
public Money(long cents, String currency) {
this.cents = cents;
this.currency = currency.toUpperCase(Locale.ROOT); // "eur" and "EUR" are the same currency
}
public long cents() {
return cents;
}
public String currency() {
return currency;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Money other)) {
return false; // also for null
}
return cents == other.cents && currency.equals(other.currency);
}
@Override
public int hashCode() {
return Objects.hash(cents, currency); // the same fields as equals
}
@Override
public String toString() {
return "Money[" + cents + " " + currency + "]";
}
public static int countDistinct(List<Long> amounts, List<String> currencies) {
Set<Money> seen = new HashSet<>();
for (int i = 0; i < amounts.size(); i++) {
seen.add(new Money(amounts.get(i), currencies.get(i)));
}
return seen.size();
}
}
MoneyTest.java 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
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 MoneyTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-equal", List.of(1250L, 1250L), List.of("EUR", "EUR"), 1),
Arguments.of("different-amounts", List.of(100L, 200L, 100L), List.of("USD", "USD", "USD"), 2),
Arguments.of("mixed", List.of(500L, 500L, 500L, 700L), List.of("EUR", "USD", "EUR", "EUR"), 3),
Arguments.of("empty", List.of(), List.of(), 0),
Arguments.of("case", List.of(999L, 999L, 999L), List.of("gbp", "GBP", "Gbp"), 1),
Arguments.of("other-currency", List.of(0L, 0L, 0L), List.of("EUR", "USD", "JPY"), 3),
Arguments.of("negative", List.of(-5L, 5L, -5L), List.of("EUR", "EUR", "EUR"), 2),
Arguments.of(
"limit",
List.of(1_000_000_000_000L, -1_000_000_000_000L, 1_000_000_000_000L),
List.of("usd", "USD", "USD"),
2));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void countDistinct(String name, List<Long> amounts, List<String> currencies, int want) {
assertEquals(want, Money.countDistinct(amounts, currencies), name);
}
@Test
void equalityRules() {
Money a = new Money(1250, "EUR");
Money b = new Money(1250, "eur");
assertTrue(a.equals(a));
assertTrue(a.equals(b) && b.equals(a));
assertEquals(a.hashCode(), b.hashCode());
assertNotEquals(a, new Money(1251, "EUR"));
assertNotEquals(a, new Money(1250, "USD"));
assertFalse(a.equals(null));
assertFalse(a.equals("1250 EUR"));
assertFalse(a == b);
}
@Test
void mapKey() {
Map<Money, String> names = Map.of(new Money(500, "USD"), "lunch");
assertEquals("lunch", names.get(new Money(500, "usd")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#include "money.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
Money money_make(int64_t cents, const char *currency) {
Money m;
memset(&m, 0, sizeof m);
m.cents = cents;
for (int i = 0; i < 3 && currency[i] != '\0'; i++) {
m.currency[i] = (char)toupper((unsigned char)currency[i]); // "eur" and "EUR" are the same currency
}
return m;
}
// Compare the fields, not the bytes: memcmp would also compare the padding of the struct.
bool money_equal(const Money *a, const Money *b) {
return a->cents == b->cents && strcmp(a->currency, b->currency) == 0;
}
// FNV-1a over the same fields as money_equal, so equal values have equal hashes.
uint64_t money_hash(const Money *m) {
uint64_t h = 14695981039346656037u;
uint64_t c = (uint64_t)m->cents;
for (int i = 0; i < 8; i++) {
h = (h ^ ((c >> (8 * i)) & 0xff)) * 1099511628211u;
}
for (const char *p = m->currency; *p != '\0'; p++) {
h = (h ^ (unsigned char)*p) * 1099511628211u;
}
return h;
}
// A hash set with open addressing. Returns -1 if memory runs out.
int count_distinct(const int64_t *amounts, const char *const *currencies, int n) {
size_t size = 16;
while (size < 2 * (size_t)n) {
size *= 2;
}
Money *slots = malloc(size * sizeof *slots);
bool *used = calloc(size, sizeof *used);
if (slots == NULL || used == NULL) {
free(slots);
free(used);
return -1;
}
int count = 0;
for (int i = 0; i < n; i++) {
Money m = money_make(amounts[i], currencies[i]);
size_t j = (size_t)(money_hash(&m) & (size - 1));
while (used[j] && !money_equal(&slots[j], &m)) {
j = (j + 1) & (size - 1);
}
if (!used[j]) {
used[j] = true;
slots[j] = m;
count++;
}
}
free(slots);
free(used);
return count;
}
money.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#ifndef MONEY_H
#define MONEY_H
#include <stdbool.h>
#include <stdint.h>
// An amount in cents and an upper-case 3-letter currency code.
typedef struct {
int64_t cents;
char currency[4];
} Money;
Money money_make(int64_t cents, const char *currency);
bool money_equal(const Money *a, const Money *b);
uint64_t money_hash(const Money *m);
int count_distinct(const int64_t *amounts, const char *const *currencies, int n);
#endif
test_money.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
#include "money.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const int64_t *amounts, const char *const *currencies, int n, int want) {
int got = count_distinct(amounts, currencies, n);
if (got != want) {
fprintf(stderr, "case %s failed: got %d, want %d\n", name, got, want);
failures++;
}
}
static void expect(const char *name, bool ok) {
if (!ok) {
fprintf(stderr, "check %s failed\n", name);
failures++;
}
}
int main(void) {
check("two-equal", (int64_t[]){1250, 1250}, (const char *[]){"EUR", "EUR"}, 2, 1);
check("different-amounts", (int64_t[]){100, 200, 100}, (const char *[]){"USD", "USD", "USD"}, 3, 2);
check("mixed", (int64_t[]){500, 500, 500, 700}, (const char *[]){"EUR", "USD", "EUR", "EUR"}, 4, 3);
check("empty", NULL, NULL, 0, 0);
check("case", (int64_t[]){999, 999, 999}, (const char *[]){"gbp", "GBP", "Gbp"}, 3, 1);
check("other-currency", (int64_t[]){0, 0, 0}, (const char *[]){"EUR", "USD", "JPY"}, 3, 3);
check("negative", (int64_t[]){-5, 5, -5}, (const char *[]){"EUR", "EUR", "EUR"}, 3, 2);
check("limit", (int64_t[]){1000000000000, -1000000000000, 1000000000000}, (const char *[]){"usd", "USD", "USD"}, 3, 2);
Money a = money_make(1250, "EUR"), b = money_make(1250, "eur");
expect("reflexive", money_equal(&a, &a));
expect("symmetric", money_equal(&a, &b) && money_equal(&b, &a));
expect("hash", money_hash(&a) == money_hash(&b));
Money c = money_make(1251, "EUR"), d = money_make(1250, "USD");
expect("other amount", !money_equal(&a, &c));
expect("other currency", !money_equal(&a, &d));
if (failures == 0) {
printf("all cases passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
using System;
using System.Collections.Generic;
/// <summary>An amount in cents and a currency code. Sealed, so no subclass can break Equals.</summary>
public sealed class Money : IEquatable<Money>
{
public long Cents { get; }
public string Currency { get; }
public Money(long cents, string currency)
{
Cents = cents;
Currency = currency.ToUpperInvariant(); // "eur" and "EUR" are the same currency
}
public bool Equals(Money? other) =>
other is not null && Cents == other.Cents && Currency == other.Currency;
public override bool Equals(object? obj) => Equals(obj as Money);
public override int GetHashCode() => HashCode.Combine(Cents, Currency); // the same fields as Equals
public override string ToString() => $"Money({Cents}, {Currency})";
// For a class, == compares references unless the class defines it.
public static bool operator ==(Money? left, Money? right) =>
left is null ? right is null : left.Equals(right);
public static bool operator !=(Money? left, Money? right) => !(left == right);
public static int CountDistinct(IReadOnlyList<long> amounts, IReadOnlyList<string> currencies)
{
var seen = new HashSet<Money>();
for (var i = 0; i < amounts.Count; i++)
{
seen.Add(new Money(amounts[i], currencies[i]));
}
return seen.Count;
}
}
MoneyTests.cs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
using System.Collections.Generic;
using Xunit;
public sealed class MoneyTests
{
public static TheoryData<string, long[], string[], int> Cases => new()
{
{ "two-equal", new long[] { 1250, 1250 }, new[] { "EUR", "EUR" }, 1 },
{ "different-amounts", new long[] { 100, 200, 100 }, new[] { "USD", "USD", "USD" }, 2 },
{ "mixed", new long[] { 500, 500, 500, 700 }, new[] { "EUR", "USD", "EUR", "EUR" }, 3 },
{ "empty", new long[] { }, new string[] { }, 0 },
{ "case", new long[] { 999, 999, 999 }, new[] { "gbp", "GBP", "Gbp" }, 1 },
{ "other-currency", new long[] { 0, 0, 0 }, new[] { "EUR", "USD", "JPY" }, 3 },
{ "negative", new long[] { -5, 5, -5 }, new[] { "EUR", "EUR", "EUR" }, 2 },
{ "limit", new long[] { 1_000_000_000_000, -1_000_000_000_000, 1_000_000_000_000 }, new[] { "usd", "USD", "USD" }, 2 },
};
[Theory]
[MemberData(nameof(Cases))]
public void CountDistinct(string name, long[] amounts, string[] currencies, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Money.CountDistinct(amounts, currencies));
}
[Fact]
public void EqualityRules()
{
var a = new Money(1250, "EUR");
var b = new Money(1250, "eur");
Assert.True(a.Equals(a));
Assert.True(a.Equals(b) && b.Equals(a));
Assert.True(a == b);
Assert.False(a != b);
Assert.False(ReferenceEquals(a, b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.NotEqual(a, new Money(1251, "EUR"));
Assert.NotEqual(a, new Money(1250, "USD"));
Assert.False(a.Equals(null));
Assert.False(a.Equals((object)"1250 EUR"));
Assert.False(a == null);
}
[Fact]
public void DictionaryKey()
{
var names = new Dictionary<Money, string> { [new Money(500, "USD")] = "lunch" };
Assert.Equal("lunch", names[new Money(500, "usd")]);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
export class Money {
#cents;
#currency;
constructor(cents, currency) {
this.#cents = cents;
this.#currency = currency.toUpperCase(); // "eur" and "EUR" are the same currency
Object.freeze(this);
}
get cents() {
return this.#cents;
}
get currency() {
return this.#currency;
}
equals(other) {
return other instanceof Money && this.#cents === other.#cents && this.#currency === other.#currency;
}
// Set, Map and === compare objects by identity. Equal values have equal keys, so code
// that needs value equality in a Set or a Map stores the key.
key() {
return `${this.#currency} ${this.#cents}`;
}
toString() {
return `Money(${this.#cents}, ${this.#currency})`;
}
}
export function countDistinct(amounts, currencies) {
const seen = new Set();
amounts.forEach((amount, i) => seen.add(new Money(amount, currencies[i]).key()));
return seen.size;
}
money.test.js 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Money, countDistinct } from "./money.js";
const cases = [
["two-equal", [1250, 1250], ["EUR", "EUR"], 1],
["different-amounts", [100, 200, 100], ["USD", "USD", "USD"], 2],
["mixed", [500, 500, 500, 700], ["EUR", "USD", "EUR", "EUR"], 3],
["empty", [], [], 0],
["case", [999, 999, 999], ["gbp", "GBP", "Gbp"], 1],
["other-currency", [0, 0, 0], ["EUR", "USD", "JPY"], 3],
["negative", [-5, 5, -5], ["EUR", "EUR", "EUR"], 2],
["limit", [1e12, -1e12, 1e12], ["usd", "USD", "USD"], 2],
];
for (const [name, amounts, currencies, want] of cases) {
test(name, () => {
assert.equal(countDistinct(amounts, currencies), want);
});
}
test("equality rules", () => {
const a = new Money(1250, "EUR");
const b = new Money(1250, "eur");
assert.ok(a.equals(a));
assert.ok(a.equals(b) && b.equals(a));
assert.ok(!a.equals(new Money(1251, "EUR")));
assert.ok(!a.equals(new Money(1250, "USD")));
assert.ok(!a.equals(null));
assert.ok(!a.equals({ cents: 1250, currency: "EUR" }));
assert.equal(a.key(), b.key());
});
test("=== stays identity", () => {
assert.notEqual(new Money(1, "EUR"), new Money(1, "EUR"));
assert.equal(new Set([new Money(1, "EUR"), new Money(1, "EUR")]).size, 2);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
export class Money {
readonly #cents: number;
readonly #currency: string;
constructor(cents: number, currency: string) {
this.#cents = cents;
this.#currency = currency.toUpperCase(); // "eur" and "EUR" are the same currency
Object.freeze(this);
}
get cents(): number {
return this.#cents;
}
get currency(): string {
return this.#currency;
}
equals(other: unknown): boolean {
return other instanceof Money && this.#cents === other.#cents && this.#currency === other.#currency;
}
// Set, Map and === compare objects by identity, so value equality in a Set or a Map uses this key.
key(): string {
return `${this.#currency} ${this.#cents}`;
}
toString(): string {
return `Money(${this.#cents}, ${this.#currency})`;
}
}
export function countDistinct(amounts: number[], currencies: string[]): number {
const seen = new Set<string>();
amounts.forEach((amount, i) => seen.add(new Money(amount, currencies[i]).key()));
return seen.size;
}
money.test.ts 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Money, countDistinct } from "./money.ts";
const cases: [string, number[], string[], number][] = [
["two-equal", [1250, 1250], ["EUR", "EUR"], 1],
["different-amounts", [100, 200, 100], ["USD", "USD", "USD"], 2],
["mixed", [500, 500, 500, 700], ["EUR", "USD", "EUR", "EUR"], 3],
["empty", [], [], 0],
["case", [999, 999, 999], ["gbp", "GBP", "Gbp"], 1],
["other-currency", [0, 0, 0], ["EUR", "USD", "JPY"], 3],
["negative", [-5, 5, -5], ["EUR", "EUR", "EUR"], 2],
["limit", [1e12, -1e12, 1e12], ["usd", "USD", "USD"], 2],
];
for (const [name, amounts, currencies, want] of cases) {
test(name, () => {
assert.equal(countDistinct(amounts, currencies), want);
});
}
test("equality rules", () => {
const a = new Money(1250, "EUR");
const b = new Money(1250, "eur");
assert.ok(a.equals(a));
assert.ok(a.equals(b) && b.equals(a));
assert.ok(!a.equals(new Money(1251, "EUR")));
assert.ok(!a.equals(new Money(1250, "USD")));
assert.ok(!a.equals(null));
assert.ok(!a.equals({ cents: 1250, currency: "EUR" }));
assert.equal(a.key(), b.key());
});
test("=== stays identity", () => {
assert.notEqual(new Money(1, "EUR"), new Money(1, "EUR"));
assert.equal(new Set([new Money(1, "EUR"), new Money(1, "EUR")]).size, 2);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
// Package money shows equality for a Go struct. The fields are comparable, so == compares
// them, and a Money value can be a map key. The constructor makes the equal values identical.
package money
import "strings"
// Money is an amount in cents and an upper-case currency code.
type Money struct {
cents int64
currency string
}
// New returns a Money value. "eur" and "EUR" are the same currency.
func New(cents int64, currency string) Money {
return Money{cents: cents, currency: strings.ToUpper(currency)}
}
// Equal reports whether m and other have the same amount and currency.
func (m Money) Equal(other Money) bool {
return m == other
}
// CountDistinct returns the number of different Money values.
func CountDistinct(amounts []int64, currencies []string) int {
seen := make(map[Money]struct{}, len(amounts))
for i, amount := range amounts {
seen[New(amount, currencies[i])] = struct{}{}
}
return len(seen)
}
money_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
package money
import "testing"
var cases = []struct {
name string
amounts []int64
currencies []string
want int
}{
{"two-equal", []int64{1250, 1250}, []string{"EUR", "EUR"}, 1},
{"different-amounts", []int64{100, 200, 100}, []string{"USD", "USD", "USD"}, 2},
{"mixed", []int64{500, 500, 500, 700}, []string{"EUR", "USD", "EUR", "EUR"}, 3},
{"empty", []int64{}, []string{}, 0},
{"case", []int64{999, 999, 999}, []string{"gbp", "GBP", "Gbp"}, 1},
{"other-currency", []int64{0, 0, 0}, []string{"EUR", "USD", "JPY"}, 3},
{"negative", []int64{-5, 5, -5}, []string{"EUR", "EUR", "EUR"}, 2},
{"limit", []int64{1e12, -1e12, 1e12}, []string{"usd", "USD", "USD"}, 2},
}
func TestCountDistinct(t *testing.T) {
for _, c := range cases {
if got := CountDistinct(c.amounts, c.currencies); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
func TestEqualityRules(t *testing.T) {
a, b := New(1250, "EUR"), New(1250, "eur")
if !a.Equal(a) || !a.Equal(b) || !b.Equal(a) || a != b {
t.Fatal("equal values are not equal")
}
if a.Equal(New(1251, "EUR")) || a.Equal(New(1250, "USD")) {
t.Fatal("different values are equal")
}
names := map[Money]string{New(500, "USD"): "lunch"}
if names[New(500, "usd")] != "lunch" {
t.Fatal("map lookup with an equal key failed")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
use std::collections::HashSet;
/// An amount in cents and an upper-case currency code.
/// The derived PartialEq, Eq and Hash use the same two fields, so they agree.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Money {
cents: i64,
currency: String,
}
impl Money {
/// "eur" and "EUR" are the same currency.
pub fn new(cents: i64, currency: &str) -> Self {
Money { cents, currency: currency.to_ascii_uppercase() }
}
pub fn cents(&self) -> i64 {
self.cents
}
pub fn currency(&self) -> &str {
&self.currency
}
}
/// Returns the number of different Money values.
pub fn count_distinct(amounts: &[i64], currencies: &[&str]) -> usize {
amounts
.iter()
.zip(currencies)
.map(|(&amount, currency)| Money::new(amount, currency))
.collect::<HashSet<_>>()
.len()
}
tests/money_test.rs 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-equality-for-a-type/.
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use algo_implement_equality_for_a_type::{count_distinct, Money};
#[test]
fn cases() {
let cases: Vec<(&str, Vec<i64>, Vec<&str>, usize)> = vec![
("two-equal", vec![1250, 1250], vec!["EUR", "EUR"], 1),
("different-amounts", vec![100, 200, 100], vec!["USD", "USD", "USD"], 2),
("mixed", vec![500, 500, 500, 700], vec!["EUR", "USD", "EUR", "EUR"], 3),
("empty", vec![], vec![], 0),
("case", vec![999, 999, 999], vec!["gbp", "GBP", "Gbp"], 1),
("other-currency", vec![0, 0, 0], vec!["EUR", "USD", "JPY"], 3),
("negative", vec![-5, 5, -5], vec!["EUR", "EUR", "EUR"], 2),
("limit", vec![1_000_000_000_000, -1_000_000_000_000, 1_000_000_000_000], vec!["usd", "USD", "USD"], 2),
];
for (name, amounts, currencies, want) in cases {
assert_eq!(count_distinct(&amounts, ¤cies), want, "{name}");
}
}
fn hash_of(m: &Money) -> u64 {
let mut h = DefaultHasher::new();
m.hash(&mut h);
h.finish()
}
#[test]
fn equality_rules() {
let a = Money::new(1250, "EUR");
let b = Money::new(1250, "eur");
assert_eq!(a, a.clone());
assert!(a == b && b == a);
assert_eq!(hash_of(&a), hash_of(&b));
assert_ne!(a, Money::new(1251, "EUR"));
assert_ne!(a, Money::new(1250, "USD"));
let names = HashMap::from([(Money::new(500, "USD"), "lunch")]);
assert_eq!(names[&Money::new(500, "usd")], "lunch");
}
References
- Object (Java SE 21 & JDK 21), API documentation, equals; hashCode
- Data model, The Python Language Reference, 3.3.1 Basic customization
- How to define value equality for a class or struct, C# programming guide, Value types, reference types, and equality defaults; Use records for value equality
- The Go Programming Language Specification, Comparison operators
- Eq trait, Rust standard library, Description
- Hash trait, Rust standard library, Hash and Eq
- Default comparisons, cppreference.com, Introduction
- Equality comparisons and sameness, MDN, Introduction
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag ZX1AWQ Edit this page History Report an error Markdown