Taskintro
Define a method on a type
Also called add a method to a struct, method on a record, receiver function, impl block, member function on a struct, method on a value type.
Define an immutable Point type with a translate method that returns another point and a manhattan method that takes a second point, using records, structs and receivers.
- Evidence
- Code in 9 languages
Task
Define a type Point with two integer fields, x and y, and two methods. translate(dx, dy) returns another point, moved by dx and dy, and leaves the original point as it was. manhattan(other) takes a second point and returns the grid distance |x - other.x| + |y - other.y|. Then use them. The function point_report(x, y, dx, dy) makes the point p = (x, y), computes q = p.translate(dx, dy), and returns [q.x, q.y, p.manhattan(q), q.manhattan(origin)]. For example, point_report(1, 2, 3, 4) is [4, 6, 7, 10].
Each input has an absolute value of 100,000,000 or less, so every result fits in a signed 32-bit integer. The tests also check that translate does not change p.
The type holds plain data, so each solution uses the lightest kind of type that a language offers for it: a record, a data class or a struct, not a full class. See Define a class for a class with changing state.
Solutions
| Language | The type | Where the methods go | The receiver |
|---|---|---|---|
| Python | @dataclass(frozen=True) class Point |
the class body | self, the first parameter |
| JavaScript | class Point, frozen in the constructor |
the class body | this |
| TypeScript | class Point with readonly fields |
the class body | this |
| Java | record Point(int x, int y) |
the record body | this, hidden |
| C# | readonly record struct Point(int X, int Y) |
the record body | this, hidden |
| C++ | struct Point |
member functions, declared in the struct | this; const member functions |
| Go | type Point struct |
method declarations beside the type | a named value receiver p Point |
| Rust | struct Point, Copy |
an impl Point block |
self or &self |
| C | struct point |
functions named point_... |
the struct as the first parameter |
- Python and Java generate the boilerplate. The
dataclassesmodule provides "a decorator and functions for automatically adding generated special methods such as init() and repr() to user-defined classes".1 Withfrozen=True, an assignment such asp.x = 9raisesFrozenInstanceError. A Java record does the same work: each record component corresponds to "a private field declared implicitly, and a public accessor method declared explicitly or implicitly",2 soq.x()reads the field. The methodstranslateandmanhattango in the record body like the methods of any class, and the record also getsequals,hashCodeandtoString. - C# uses a record struct. "The record struct syntax defines a value type."3 A
Pointis copied on assignment, andreadonlymakes every field read-only, soTranslatemust return a value made withnew. C# methods "are declared in a class, struct, or interface",4 and a record struct is a struct. For a small value change, thewithexpression copies a record with some properties changed:p with { X = 0 }. - JavaScript has no record type. The solution uses a class and calls
Object.freeze(this)in the constructor. "Methods are defined on the prototype of each class instance and are shared by all instances."5 TypeScript marks the fieldsreadonly, which the compiler checks; the object is not frozen at run time. - Go declares methods beside the type. A method declaration "associates the method with the receiver's base type", and the base type "must be declared in the same package as the method".6 Any defined type can have methods, not only a struct: see the pitfall below.
TranslateandManhattanhave value receivers, so each call gets a copy of the point and cannot change the caller's point. TwoPointvalues compare with==, because all their fields are comparable. - Rust puts methods in an
implblock. "Everything within this impl block will be associated with the Rectangle type", says the Rust book of its own example,7 and the same holds forimpl Point.translatetakesselfby value; becausePointderivesCopy, the call copies the point and the caller can still usep.manhattantakes&selfand&Point. The Reference allows inherent methods only where the type is defined: "An implementing type must be defined within the same crate as the original type definition."8 - C++ marks the methods that only read. A
structis a class whose members are public by default.translateandmanhattanareconstmember functions, sothishas the typeconst Point*in them, and they can be called on aconst Point.9 The defaultedoperator==compares the fields. - C passes the struct by value.
point_translate(struct point p, int dx, int dy)gets a copy of the point and returns another one. A struct of twointfields is small, so the copy costs about as much as passing a pointer, and the function cannot change the caller's point.
Alternatives
- Methods that change the point. If the point must change in place, give the method a pointer receiver in Go,
&mut selfin Rust, and dropfrozen,readonlyor the record. Define a class shows this withscale. - Free functions. Go, Rust and C++ also allow a plain function
manhattan(p, q). A method fits when the operation belongs to the type and should show in its documentation and in code completion; a free function fits when both arguments have equal parts, as in a distance.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero-move:translate(0, 0)returns an equal point, and the distance betweenpandqis 0.negative: negative coordinates and moves;absmakes each part of the distance positive.origin: the move ends at the origin, so the last result is 0.limit: every input is 100,000,000 in absolute value. The largest result is 400,000,000, which fits in a signed 32-bit integer. Inputs of up to 1,000,000,000 would not fit: a coordinate of 2,000,000,000 after the move is still below 2^31 - 1, but the distance to the origin, 4,000,000,000, is not.
Pitfalls
- Go and Rust allow methods only on local types. A Go method cannot be declared on
intor on a type from another package, and a Rustimpl i32block is an error. Go code defines a local type with the built-in type as its underlying type, and that type can have methods even when it is not a struct:
package main
import "fmt"
// Celsius is a defined type with float64 as its underlying type.
type Celsius float64
func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 }
// String makes Celsius a fmt.Stringer, so Println calls it.
func (c Celsius) String() string { return fmt.Sprintf("%.1f C", float64(c)) }
// Path is a defined slice type, and it can have methods too.
type Path []Celsius
func (p Path) Max() Celsius {
m := p[0]
for _, c := range p[1:] {
m = max(m, c)
}
return m
}
func main() {
t := Celsius(21.5)
fmt.Println(t)
fmt.Printf("%.1f\n", t.Fahrenheit())
fmt.Println(Path{18, 23.5, 21}.Max())
}
21.5 C
70.7
23.5 C
Rust code declares a local trait and implements it for the foreign type, or wraps the type in a newtype:
// A trait adds methods to a type of another crate, here the built-in i32.
trait Parity {
fn is_even(&self) -> bool;
}
impl Parity for i32 {
fn is_even(&self) -> bool {
self % 2 == 0
}
}
// A newtype wraps a type of another crate in a local type with its own methods.
struct Meters(f64);
impl Meters {
fn to_feet(&self) -> f64 {
self.0 / 0.3048
}
}
fn main() {
println!("{} {}", 4.is_even(), 7.is_even());
println!("{:.2}", Meters(100.0).to_feet());
}
true false
328.08
- A Go value receiver and a pointer receiver do not mix freely. A method with a pointer receiver
*Pointis not in the method set ofPoint, so aPointvalue in an interface variable does not have it. Choose one kind of receiver for all methods of a type. - A mutable struct in a C# collection or property. Without
readonly, a method that changes a struct changes a copy when the struct comes from a property or a list element. Thereadonly record structavoids this, because no method can change the fields. - A frozen object in JavaScript is shallow.
Object.freezestops assignments toxandy, but if a field holds an array, the array can still change. The same holds for Python'sfrozen=Trueand for Java records with a list component. - TypeScript
readonlyis a compile-time check. JavaScript code, or TypeScript code that uses a type assertion, can still assign the field at run time. ==on JavaScript objects compares identity. TwoPointobjects with the same fields are not equal under===, because JavaScript classes have no generated equality. Java records, C# records, Python dataclasses, Go structs and the C++ defaultedoperator==compare the fields. In JavaScript, compare the fields or write anequalsmethod.
Related tasks
- Define a class defines a class whose methods change its state.
- Method explains how a call finds the method and passes the receiver.
- Classes and instances explains what a class is and how instances share its methods.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-method-on-a-type/.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
"""A point on a grid. The dataclass writes __init__, __repr__ and __eq__."""
x: int
y: int
def translate(self, dx, dy):
"""Return the point moved by (dx, dy). The point itself does not change."""
return Point(self.x + dx, self.y + dy)
def manhattan(self, other):
"""Return the grid distance |dx| + |dy| to another point."""
return abs(self.x - other.x) + abs(self.y - other.y)
ORIGIN = Point(0, 0)
def point_report(x, y, dx, dy):
p = Point(x, y)
q = p.translate(dx, dy)
return [q.x, q.y, p.manhattan(q), q.manhattan(ORIGIN)]
test_point.py 32 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-method-on-a-type/.
import dataclasses
import pytest
from point import Point, point_report
CASES = {
"right-and-up": ((1, 2, 3, 4), [4, 6, 7, 10]),
"mixed-signs": ((5, -1, -2, 3), [3, 2, 5, 5]),
"zero-move": ((7, -3, 0, 0), [7, -3, 0, 10]),
"negative": ((-2, -5, -3, -1), [-5, -6, 4, 11]),
"origin": ((2, 3, -2, -3), [0, 0, 5, 0]),
"limit": ((100000000, -100000000, 100000000, -100000000), [200000000, -200000000, 200000000, 400000000]),
}
@pytest.mark.parametrize("name", CASES)
def test_point_report(name):
args, want = CASES[name]
assert point_report(*args) == want
def test_translate_returns_another_point():
p = Point(1, 2)
q = p.translate(3, 4)
assert p == Point(1, 2)
assert q == Point(4, 6)
with pytest.raises(dataclasses.FrozenInstanceError):
p.x = 9
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#include "point.hpp"
#include <cstdlib>
Point Point::translate(int dx, int dy) const {
return Point{x + dx, y + dy};
}
int Point::manhattan(const Point &other) const {
return std::abs(x - other.x) + std::abs(y - other.y);
}
std::vector<int> point_report(int x, int y, int dx, int dy) {
const Point origin{0, 0};
const Point p{x, y};
const Point q = p.translate(dx, dy);
return {q.x, q.y, p.manhattan(q), q.manhattan(origin)};
}
point.hpp 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#ifndef POINT_HPP
#define POINT_HPP
#include <vector>
// A point on a grid. A struct is a class whose members are public by default,
// and it can have member functions like any class.
struct Point {
int x;
int y;
// Returns the point moved by (dx, dy). const: it does not change *this.
Point translate(int dx, int dy) const;
// Returns the grid distance |dx| + |dy| to another point.
int manhattan(const Point &other) const;
bool operator==(const Point &other) const = default;
};
std::vector<int> point_report(int x, int y, int dx, int dy);
#endif
test_point.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#include "point.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, int x, int y, int dx, int dy, const std::vector<int> &want) {
if (point_report(x, y, dx, dy) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("right-and-up", 1, 2, 3, 4, {4, 6, 7, 10});
check("mixed-signs", 5, -1, -2, 3, {3, 2, 5, 5});
check("zero-move", 7, -3, 0, 0, {7, -3, 0, 10});
check("negative", -2, -5, -3, -1, {-5, -6, 4, 11});
check("origin", 2, 3, -2, -3, {0, 0, 5, 0});
check("limit", 100000000, -100000000, 100000000, -100000000, {200000000, -200000000, 200000000, 400000000});
const Point p{1, 2};
const Point q = p.translate(3, 4);
if (!(p == Point{1, 2}) || !(q == Point{4, 6})) {
std::cerr << "case another-point failed\n";
failures++;
}
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
import java.util.List;
/** A point on a grid. A record has final fields, a constructor, equals and toString. */
public record Point(int x, int y) {
static final Point ORIGIN = new Point(0, 0);
/** Returns the point moved by (dx, dy). */
public Point translate(int dx, int dy) {
return new Point(x + dx, y + dy);
}
/** Returns the grid distance |dx| + |dy| to another point. */
public int manhattan(Point other) {
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
public static List<Integer> pointReport(int x, int y, int dx, int dy) {
Point p = new Point(x, y);
Point q = p.translate(dx, dy);
return List.of(q.x(), q.y(), p.manhattan(q), q.manhattan(ORIGIN));
}
}
PointTest.java 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
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 PointTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("right-and-up", 1, 2, 3, 4, List.of(4, 6, 7, 10)),
Arguments.of("mixed-signs", 5, -1, -2, 3, List.of(3, 2, 5, 5)),
Arguments.of("zero-move", 7, -3, 0, 0, List.of(7, -3, 0, 10)),
Arguments.of("negative", -2, -5, -3, -1, List.of(-5, -6, 4, 11)),
Arguments.of("origin", 2, 3, -2, -3, List.of(0, 0, 5, 0)),
Arguments.of(
"limit",
100000000,
-100000000,
100000000,
-100000000,
List.of(200000000, -200000000, 200000000, 400000000)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void pointReport(String name, int x, int y, int dx, int dy, List<Integer> want) {
assertEquals(want, Point.pointReport(x, y, dx, dy));
}
@Test
void translateReturnsAnotherPoint() {
Point p = new Point(1, 2);
Point q = p.translate(3, 4);
assertEquals(new Point(1, 2), p);
assertEquals(new Point(4, 6), q);
assertEquals("Point[x=4, y=6]", q.toString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#include "point.h"
#include <stdlib.h>
struct point point_translate(struct point p, int dx, int dy) {
return (struct point){p.x + dx, p.y + dy};
}
int point_manhattan(struct point p, struct point q) {
return abs(p.x - q.x) + abs(p.y - q.y);
}
void point_report(int x, int y, int dx, int dy, int out[4]) {
const struct point origin = {0, 0};
struct point p = {x, y};
struct point q = point_translate(p, dx, dy);
out[0] = q.x;
out[1] = q.y;
out[2] = point_manhattan(p, q);
out[3] = point_manhattan(q, origin);
}
point.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#ifndef POINT_H
#define POINT_H
// C has no methods. A function whose first parameter is the struct plays the
// part of a method, and the name prefix point_ groups the functions.
struct point {
int x;
int y;
};
// point_translate returns p moved by (dx, dy). p is passed by value.
struct point point_translate(struct point p, int dx, int dy);
// point_manhattan returns the grid distance |dx| + |dy| between p and q.
int point_manhattan(struct point p, struct point q);
// point_report writes [q.x, q.y, manhattan(p, q), manhattan(q, origin)] to
// out[0] to out[3], where p = (x, y) and q = point_translate(p, dx, dy).
void point_report(int x, int y, int dx, int dy, int out[4]);
#endif
test_point.c 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
#include "point.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, int x, int y, int dx, int dy, int a, int b, int c, int d) {
const int want[4] = {a, b, c, d};
int got[4];
point_report(x, y, dx, dy, got);
if (memcmp(got, want, sizeof want) != 0) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
int main(void) {
check("right-and-up", 1, 2, 3, 4, 4, 6, 7, 10);
check("mixed-signs", 5, -1, -2, 3, 3, 2, 5, 5);
check("zero-move", 7, -3, 0, 0, 7, -3, 0, 10);
check("negative", -2, -5, -3, -1, -5, -6, 4, 11);
check("origin", 2, 3, -2, -3, 0, 0, 5, 0);
check("limit", 100000000, -100000000, 100000000, -100000000, 200000000, -200000000, 200000000, 400000000);
// point_translate gets a copy, so p does not change.
struct point p = {1, 2};
struct point q = point_translate(p, 3, 4);
if (p.x != 1 || p.y != 2 || q.x != 4 || q.y != 6) {
fprintf(stderr, "case another-point failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
using System;
/// <summary>A point on a grid. A readonly record struct is a value type with equality and ToString.</summary>
public readonly record struct Point(int X, int Y)
{
public static readonly Point Origin = new(0, 0);
/// <summary>Returns the point moved by (dx, dy).</summary>
public Point Translate(int dx, int dy) => new(X + dx, Y + dy);
/// <summary>Returns the grid distance |dx| + |dy| to another point.</summary>
public int Manhattan(Point other) => Math.Abs(X - other.X) + Math.Abs(Y - other.Y);
public static int[] Report(int x, int y, int dx, int dy)
{
var p = new Point(x, y);
var q = p.Translate(dx, dy);
return [q.X, q.Y, p.Manhattan(q), q.Manhattan(Origin)];
}
}
PointTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
using Xunit;
public sealed class PointTests
{
public static TheoryData<string, int, int, int, int, int[]> Cases => new()
{
{ "right-and-up", 1, 2, 3, 4, new[] { 4, 6, 7, 10 } },
{ "mixed-signs", 5, -1, -2, 3, new[] { 3, 2, 5, 5 } },
{ "zero-move", 7, -3, 0, 0, new[] { 7, -3, 0, 10 } },
{ "negative", -2, -5, -3, -1, new[] { -5, -6, 4, 11 } },
{ "origin", 2, 3, -2, -3, new[] { 0, 0, 5, 0 } },
{ "limit", 100000000, -100000000, 100000000, -100000000, new[] { 200000000, -200000000, 200000000, 400000000 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Report(string name, int x, int y, int dx, int dy, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Point.Report(x, y, dx, dy));
}
[Fact]
public void TranslateReturnsAnotherPoint()
{
var p = new Point(1, 2);
var q = p.Translate(3, 4);
Assert.Equal(new Point(1, 2), p);
Assert.Equal(new Point(4, 6), q);
Assert.Equal("Point { X = 4, Y = 6 }", q.ToString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
/** A point on a grid. The constructor freezes it, so methods return other points. */
export class Point {
constructor(x, y) {
this.x = x;
this.y = y;
Object.freeze(this);
}
/** Returns the point moved by (dx, dy). */
translate(dx, dy) {
return new Point(this.x + dx, this.y + dy);
}
/** Returns the grid distance |dx| + |dy| to another point. */
manhattan(other) {
return Math.abs(this.x - other.x) + Math.abs(this.y - other.y);
}
}
const ORIGIN = new Point(0, 0);
export function pointReport(x, y, dx, dy) {
const p = new Point(x, y);
const q = p.translate(dx, dy);
return [q.x, q.y, p.manhattan(q), q.manhattan(ORIGIN)];
}
point.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Point, pointReport } from "./point.js";
const cases = [
["right-and-up", [1, 2, 3, 4], [4, 6, 7, 10]],
["mixed-signs", [5, -1, -2, 3], [3, 2, 5, 5]],
["zero-move", [7, -3, 0, 0], [7, -3, 0, 10]],
["negative", [-2, -5, -3, -1], [-5, -6, 4, 11]],
["origin", [2, 3, -2, -3], [0, 0, 5, 0]],
["limit", [100000000, -100000000, 100000000, -100000000], [200000000, -200000000, 200000000, 400000000]],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.deepEqual(pointReport(...args), want);
});
}
test("translate returns another point", () => {
const p = new Point(1, 2);
const q = p.translate(3, 4);
assert.deepEqual([p.x, p.y, q.x, q.y], [1, 2, 4, 6]);
assert.throws(() => {
p.x = 9;
}, TypeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
/** A point on a grid. The fields are readonly, so methods return other points. */
export class Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
/** Returns the point moved by (dx, dy). */
translate(dx: number, dy: number): Point {
return new Point(this.x + dx, this.y + dy);
}
/** Returns the grid distance |dx| + |dy| to another point. */
manhattan(other: Point): number {
return Math.abs(this.x - other.x) + Math.abs(this.y - other.y);
}
}
const ORIGIN = new Point(0, 0);
export function pointReport(x: number, y: number, dx: number, dy: number): number[] {
const p = new Point(x, y);
const q = p.translate(dx, dy);
return [q.x, q.y, p.manhattan(q), q.manhattan(ORIGIN)];
}
point.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Point, pointReport } from "./point.ts";
const cases: [string, [number, number, number, number], number[]][] = [
["right-and-up", [1, 2, 3, 4], [4, 6, 7, 10]],
["mixed-signs", [5, -1, -2, 3], [3, 2, 5, 5]],
["zero-move", [7, -3, 0, 0], [7, -3, 0, 10]],
["negative", [-2, -5, -3, -1], [-5, -6, 4, 11]],
["origin", [2, 3, -2, -3], [0, 0, 5, 0]],
["limit", [100000000, -100000000, 100000000, -100000000], [200000000, -200000000, 200000000, 400000000]],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.deepEqual(pointReport(...args), want);
});
}
test("translate returns another point", () => {
const p = new Point(1, 2);
const q = p.translate(3, 4);
assert.deepEqual([p.x, p.y, q.x, q.y], [1, 2, 4, 6]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
// Package point declares methods on a struct type. Go has no classes: a
// method is a function with a receiver, declared beside the type.
package point
// Point is a point on a grid.
type Point struct {
X, Y int
}
// Origin is the point (0, 0).
var Origin = Point{0, 0}
// Translate returns the point moved by (dx, dy). The receiver is a copy, so
// the caller's point does not change.
func (p Point) Translate(dx, dy int) Point {
return Point{p.X + dx, p.Y + dy}
}
// Manhattan returns the grid distance |dx| + |dy| to another point.
func (p Point) Manhattan(q Point) int {
return abs(p.X-q.X) + abs(p.Y-q.Y)
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
// Report moves the point (x, y) by (dx, dy) and measures the move.
func Report(x, y, dx, dy int) []int {
p := Point{x, y}
q := p.Translate(dx, dy)
return []int{q.X, q.Y, p.Manhattan(q), q.Manhattan(Origin)}
}
point_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
package point
import (
"slices"
"testing"
)
var cases = []struct {
name string
x, y, dx, dy int
want []int
}{
{"right-and-up", 1, 2, 3, 4, []int{4, 6, 7, 10}},
{"mixed-signs", 5, -1, -2, 3, []int{3, 2, 5, 5}},
{"zero-move", 7, -3, 0, 0, []int{7, -3, 0, 10}},
{"negative", -2, -5, -3, -1, []int{-5, -6, 4, 11}},
{"origin", 2, 3, -2, -3, []int{0, 0, 5, 0}},
{"limit", 100000000, -100000000, 100000000, -100000000, []int{200000000, -200000000, 200000000, 400000000}},
}
func TestReport(t *testing.T) {
for _, c := range cases {
if got := Report(c.x, c.y, c.dx, c.dy); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestTranslateReturnsAnotherPoint(t *testing.T) {
p := Point{1, 2}
q := p.Translate(3, 4)
if p != (Point{1, 2}) || q != (Point{4, 6}) {
t.Errorf("got %v and %v", p, q)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
/// A point on a grid. `Copy` makes it a plain value, like an integer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Point {
pub x: i32,
pub y: i32,
}
pub const ORIGIN: Point = Point { x: 0, y: 0 };
impl Point {
pub fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
/// Returns the point moved by (dx, dy). `self` is taken by value, which
/// copies a `Copy` type, so the caller keeps its point.
pub fn translate(self, dx: i32, dy: i32) -> Self {
Point::new(self.x + dx, self.y + dy)
}
/// Returns the grid distance |dx| + |dy| to another point.
pub fn manhattan(&self, other: &Point) -> i32 {
(self.x - other.x).abs() + (self.y - other.y).abs()
}
}
pub fn point_report(x: i32, y: i32, dx: i32, dy: i32) -> Vec<i32> {
let p = Point::new(x, y);
let q = p.translate(dx, dy);
vec![q.x, q.y, p.manhattan(&q), q.manhattan(&ORIGIN)]
}
tests/point_test.rs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-method-on-a-type/.
use algo_define_a_method_on_a_type::{point_report, Point};
#[test]
fn cases() {
let cases: Vec<(&str, (i32, i32, i32, i32), Vec<i32>)> = vec![
("right-and-up", (1, 2, 3, 4), vec![4, 6, 7, 10]),
("mixed-signs", (5, -1, -2, 3), vec![3, 2, 5, 5]),
("zero-move", (7, -3, 0, 0), vec![7, -3, 0, 10]),
("negative", (-2, -5, -3, -1), vec![-5, -6, 4, 11]),
("origin", (2, 3, -2, -3), vec![0, 0, 5, 0]),
(
"limit",
(100000000, -100000000, 100000000, -100000000),
vec![200000000, -200000000, 200000000, 400000000],
),
];
for (name, (x, y, dx, dy), want) in cases {
assert_eq!(point_report(x, y, dx, dy), want, "{name}");
}
}
#[test]
fn translate_returns_another_point() {
let p = Point::new(1, 2);
let q = p.translate(3, 4);
assert_eq!(p, Point::new(1, 2));
assert_eq!(q, Point::new(4, 6));
}
References
- dataclasses, Data Classes, The Python Standard Library, Module contents; Frozen instances
- Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, 8.10 Record Classes
- Records, C# reference, Introduction; Nondestructive mutation
- Methods, C# programming guide, Method signatures
- Classes, MDN Web Docs, Methods
- The Go Programming Language Specification, Method declarations; Method sets
- Methods, The Rust Programming Language, Defining Methods; Associated Functions
- Implementations, The Rust Reference, Inherent implementations
- Non-static member functions, cppreference.com, const- and volatile-qualified member functions
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 QADG78 Edit this page History Report an error Markdown