Taskintro
Define a record type
Also called define a struct, define a data class, define a record class, make a record, struct type, plain data type.
Define a person record with a name and an age, build it, read its fields and make a changed copy, and get equality and printing from the language.
- Evidence
- Code in 10 languages
Task
Define a record type Person with two fields, name (a string) and age (an integer). Then use it in the function birthday(people, name). The function takes a list of people and a name. It returns a new list with the people in the same order. Each person whose name is equal to name, character for character, has the age plus 1. The other people do not change. The function must not change the input list or its records. For example, birthday([("Ada", 36), ("Alan", 41)], "Ada") is [("Ada", 37), ("Alan", 41)].
The task shows the four things that a program does with a record: it builds one, reads a field by name, makes a copy with one field changed, and compares or prints records. For the idea behind records, see Record type.
Solutions
| Language | Record type | Copy with a change | Equality and printing |
|---|---|---|---|
| Python | @dataclass(frozen=True) class Person |
replace(p, age=p.age + 1) |
made from the fields |
| JavaScript | a frozen object { name, age } |
{ ...p, age: p.age + 1 } |
by reference; write your own |
| TypeScript | type Person = { readonly name: string; readonly age: number } |
{ ...p, age: p.age + 1 } |
by reference; write your own |
| Java | record Person(String name, int age) |
new Person(name, age + 1) |
made from the components |
| C# | record Person(string Name, int Age) |
p with { Age = p.Age + 1 } |
made from the properties |
| Go | type Person struct { Name string; Age int } |
assign, then change the copy | == on each field; %+v |
| Rust | struct Person with #[derive(Clone, Debug, PartialEq, Eq)] |
Person { age: p.age + 1, ..p.clone() } |
from the derives |
| C | struct person { const char *name; int age; } |
assign, then change the copy | none; write your own |
| C++ | struct Person with operator== set to = default |
copy, then change the copy | == from the members; no printing |
| Bash | the string "name|age" |
split, change, join | string equality |
- The language writes the methods. Python's
dataclassesmodule "provides a decorator and functions for automatically adding generated special methods such as init() and repr() to user-defined classes."1 The generated__eq__"compares the class by comparing each field in order."1 For a Java record, "The implicit declaration of the Object.equals(Object) , Object.hashCode() , and Object.toString() methods are derived from all of the component fields."2 C# records "have a compiler-generated ToString method that displays the names and values of public properties and fields."3 In Rust, the derives do the same work: "The Debug trait enables debug formatting in format strings"4, and "When PartialEq is derived on structs, two instances are equal only if all fields are equal, and the instances are not equal if any fields are not equal."4 - Fields that cannot change. The solutions keep each record as it is and make a new one for the older person. With
frozen=True, "assigning to fields will generate an exception."1 A Java record class "is a shallowly immutable, transparent carrier for a fixed set of values, called the record components."2 "A positional record class and a positional readonly record struct declare init-only properties."3 In TypeScript,readonlyis a check at compile time only. The handbook says that it does not change the behavior at run time5. The JavaScript solution thus also callsObject.freeze. - A copy with one change. Python's
replace"Creates a new object of the same type as obj, replacing fields with values from changes."1 In C#, "A with expression creates a new record instance that's a copy of an existing record instance, but with specified properties and fields modified."3 In Rust, the struct update syntax fills the other fields: "The syntax .. specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance."6 It moves the fields that are notCopy, so the solution writes..p.clone(): "we can no longer use user1 after creating user2 because the String in the username field of user1 was moved into user2"6. JavaScript uses spread syntax: "You can use spread syntax to merge multiple objects into one new object."7 - Go and C copy on assignment. A Go struct "is a sequence of named elements, called fields, each of which has a name and a type."8 Assignment copies all of the fields, so the Go solution changes the copy
pin the loop and notpeople[i]. "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."8 C struct assignment copies all of the members too: the left operand can have "an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right"9. But C has no==for structs. The operands of==must be numbers or pointers, for example "both operands are pointers to qualified or unqualified versions of compatible types"9, so the C test compares the fields one at a time. - C++. "An operator== for a class type can be defined as defaulted with return type bool ."10 "The default equality comparison between x and y is performed by comparing corresponding subobjects x_i and y_i with increasing i order."10 C++ has no generated printing for a struct.
- Bash. Bash has no record type. Its arrays hold strings: "Bash provides one-dimensional indexed and associative array variables."11 The solution keeps each person as one string with a
|between the fields, so a name must not contain|.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no people give an empty list.not-found: a name that is not in the list changes nothing.duplicate-name: two people can have one name. Both get older, and the person between them does not change.zero-age: an age of 0 is a valid age.non-ascii:ZoëandZoeare two names. The comparison is on the characters, with no change to the accents.case:adais notAda. The comparison is case-sensitive.
Pitfalls
- Python a mutable default is shared. A default value in a class body is one object for all instances. "Instead, the @dataclass decorator will raise a ValueError if it detects an unhashable default parameter."1 Use
field(default_factory=list), so that each record gets a new list:
from dataclasses import dataclass, field
try:
@dataclass
class Team:
members: list = []
except ValueError as e:
print(type(e).__name__)
@dataclass
class Fixed:
members: list = field(default_factory=list)
a, b = Fixed(), Fixed()
a.members.append("Ada")
print(b.members)
ValueError
[]
- JavaScript spread and freeze are shallow. "A single spread creates a shallow copy of the original object"7, and Object.freeze does not freeze the objects inside the object "(freeze is shallow)"12. A copy of a frozen record shares its arrays with the original. Copy each nested array or object that the code will change:
const ada = Object.freeze({ name: "Ada", tags: ["math"] });
const copy = { ...ada, age: 36 };
copy.tags.push("code");
console.log(ada.tags.join(","));
const deep = { ...ada, tags: [...ada.tags] };
deep.tags.push("chess");
console.log(ada.tags.join(","));
math,code
math,code
- Java a record with a list component can change. A record is only shallowly immutable2. Its field keeps a reference to the list that the caller gave, and the caller can still change that list. Copy the list in a compact constructor:
import java.util.ArrayList;
import java.util.List;
public class Main {
record Team(String name, List<String> members) {}
record Fixed(String name, List<String> members) {
Fixed {
members = List.copyOf(members);
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Ada"));
Team t = new Team("a", list);
Fixed f = new Fixed("a", list);
list.add("Alan");
System.out.println(t.members());
System.out.println(f.members());
}
}
[Ada, Alan]
[Ada]
- C#
withcopies references. "The result of a with expression is a shallow copy."3 The copy and the original share an array property, so a change through one shows in the other:
using System;
var a = new Person("Ada", new[] { "math" });
var b = a with { Name = "Alan" };
b.Tags[0] = "code";
Console.WriteLine(a.Tags[0]);
Console.WriteLine(ReferenceEquals(a.Tags, b.Tags) ? "yes" : "no");
record Person(string Name, string[] Tags);
code
yes
- Go a slice field is shared after a copy. Struct assignment copies the slice, but "A slice is a descriptor for a contiguous segment of an underlying array"8, so the copy and the original use one array. Clone the slice before you change it:
package main
import (
"fmt"
"slices"
)
type Person struct {
Name string
Tags []string
}
func main() {
a := Person{"Ada", []string{"math"}}
b := a
b.Tags[0] = "code"
fmt.Println(a.Tags[0])
c := a
c.Tags = slices.Clone(a.Tags)
c.Tags[0] = "chess"
fmt.Println(a.Tags[0])
}
code
code
- C a pointer member copies the address, not the text. Struct assignment copies each member9. For a
char *member, that is the address, so two records point to one buffer. An array member is copied with the struct:
#include <stdio.h>
#include <string.h>
struct person {
char *name;
int age;
};
struct fixed {
char name[16];
int age;
};
int main(void) {
char buf[16] = "Ada";
struct person a = {buf, 36};
struct person b = a;
strcpy(b.name, "Bob");
printf("%s\n", a.name);
struct fixed c = {"Ada", 36};
struct fixed d = c;
strcpy(d.name, "Bob");
printf("%s\n", c.name);
return 0;
}
Bob
Ada
- C++ a defaulted
==compares pointers by address. The defaultedoperator==uses==on each member10. For aconst char *member, two equal names in two buffers are not equal. Usestd::string:
#include <iostream>
#include <string>
struct Raw {
const char *name;
int age;
bool operator==(const Raw &) const = default;
};
struct Fixed {
std::string name;
int age;
bool operator==(const Fixed &) const = default;
};
int main() {
char a[] = "Ada";
char b[] = "Ada";
std::cout << (Raw{a, 36} == Raw{b, 36} ? "yes" : "no") << '\n';
std::cout << (Fixed{a, 36} == Fixed{b, 36} ? "yes" : "no") << '\n';
}
no
yes
- Bash an unquoted expansion splits a record. "The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting."11 A name with a space then becomes two words. Put the array expansion in double quotes:
people=('Mary Ann|30' 'Ada|36')
for p in ${people[@]}; do
echo "[$p]"
done
for p in "${people[@]}"; do
echo "[$p]"
done
[Mary]
[Ann|30]
[Ada|36]
[Mary Ann|30]
[Ada|36]
Related tasks
- Use a tuple: group values by position, not by name.
- Define an enumeration: a type with a fixed set of named values.
- Use an enum with data: a type whose cases are records.
- Use a custom key in a map: a record as the key of a map.
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-record-type/.
from dataclasses import dataclass, replace
# frozen=True makes the fields read-only. The decorator also writes
# __init__, __repr__ and an __eq__ that compares the fields in order.
@dataclass(frozen=True)
class Person:
name: str
age: int
def birthday(people: list[Person], name: str) -> list[Person]:
"""Return a new list where each person called name is one year older."""
return [replace(p, age=p.age + 1) if p.name == name else p for p in people]
test_birthday.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-record-type/.
import dataclasses
import pytest
from birthday import Person, birthday
CASES = {
"first": ([("Ada", 36), ("Alan", 41)], "Ada", [("Ada", 37), ("Alan", 41)]),
"second": ([("Ada", 36), ("Alan", 41)], "Alan", [("Ada", 36), ("Alan", 42)]),
"empty": ([], "Ada", []),
"not-found": ([("Ada", 36)], "Grace", [("Ada", 36)]),
"duplicate-name": (
[("Ada", 36), ("Alan", 41), ("Ada", 9)],
"Ada",
[("Ada", 37), ("Alan", 41), ("Ada", 10)],
),
"zero-age": ([("Baby", 0)], "Baby", [("Baby", 1)]),
"non-ascii": ([("Zoë", 20), ("Zoe", 30)], "Zoë", [("Zoë", 21), ("Zoe", 30)]),
"case": ([("ada", 36)], "Ada", [("ada", 36)]),
}
@pytest.mark.parametrize("case", CASES)
def test_birthday(case):
pairs, name, want = CASES[case]
people = [Person(n, a) for n, a in pairs]
before = list(people)
got = birthday(people, name)
assert [(p.name, p.age) for p in got] == want
assert people == before
def test_equality_and_printing():
assert Person("Ada", 36) == Person("Ada", 36)
assert Person("Ada", 36) != Person("Ada", 37)
assert repr(Person("Ada", 36)) == "Person(name='Ada', age=36)"
def test_fields_are_read_only():
with pytest.raises(dataclasses.FrozenInstanceError):
Person("Ada", 36).age = 37
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#include "birthday.hpp"
std::vector<Person> birthday(const std::vector<Person> &people, const std::string &name) {
std::vector<Person> out;
out.reserve(people.size());
for (Person p : people) { // p is a copy
if (p.name == name) {
p.age++;
}
out.push_back(p);
}
return out;
}
birthday.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#pragma once
#include <string>
#include <vector>
// An aggregate struct. The defaulted operator== compares the members in
// order.
struct Person {
std::string name;
int age;
bool operator==(const Person &) const = default;
};
// birthday returns a new vector where each person called name is one year
// older.
std::vector<Person> birthday(const std::vector<Person> &people, const std::string &name);
test_birthday.cpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#include "birthday.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
using People = std::vector<Person>;
static void check(std::string_view label, const People &people, const std::string &name, const People &want) {
const People before = people;
if (birthday(people, name) != want || people != before) {
std::cerr << "case " << label << " failed\n";
failures++;
}
}
int main() {
check("first", People{{"Ada", 36}, {"Alan", 41}}, "Ada", People{{"Ada", 37}, {"Alan", 41}});
check("second", People{{"Ada", 36}, {"Alan", 41}}, "Alan", People{{"Ada", 36}, {"Alan", 42}});
check("empty", People{}, "Ada", People{});
check("not-found", People{{"Ada", 36}}, "Grace", People{{"Ada", 36}});
check("duplicate-name", People{{"Ada", 36}, {"Alan", 41}, {"Ada", 9}}, "Ada", People{{"Ada", 37}, {"Alan", 41}, {"Ada", 10}});
check("zero-age", People{{"Baby", 0}}, "Baby", People{{"Baby", 1}});
check("non-ascii", People{{"Zo\xc3\xab", 20}, {"Zoe", 30}}, "Zo\xc3\xab", People{{"Zo\xc3\xab", 21}, {"Zoe", 30}});
check("case", People{{"ada", 36}}, "Ada", People{{"ada", 36}});
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-record-type/.
import java.util.List;
final class Birthday {
private Birthday() {}
/**
* A record gets a constructor, accessors, equals, hashCode and toString from its
* components. Its fields are final.
*/
record Person(String name, int age) {
Person withAge(int newAge) {
return new Person(name, newAge);
}
}
/** Returns a new list where each person called name is one year older. */
static List<Person> birthday(List<Person> people, String name) {
return people.stream().map(p -> p.name().equals(name) ? p.withAge(p.age() + 1) : p).toList();
}
}
BirthdayTest.java 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.ArrayList;
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 BirthdayTest {
static Birthday.Person p(String name, int age) {
return new Birthday.Person(name, age);
}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("first", List.of(p("Ada", 36), p("Alan", 41)), "Ada", List.of(p("Ada", 37), p("Alan", 41))),
Arguments.of("second", List.of(p("Ada", 36), p("Alan", 41)), "Alan", List.of(p("Ada", 36), p("Alan", 42))),
Arguments.of("empty", List.of(), "Ada", List.of()),
Arguments.of("not-found", List.of(p("Ada", 36)), "Grace", List.of(p("Ada", 36))),
Arguments.of("duplicate-name", List.of(p("Ada", 36), p("Alan", 41), p("Ada", 9)), "Ada", List.of(p("Ada", 37), p("Alan", 41), p("Ada", 10))),
Arguments.of("zero-age", List.of(p("Baby", 0)), "Baby", List.of(p("Baby", 1))),
Arguments.of("non-ascii", List.of(p("Zoë", 20), p("Zoe", 30)), "Zoë", List.of(p("Zoë", 21), p("Zoe", 30))),
Arguments.of("case", List.of(p("ada", 36)), "Ada", List.of(p("ada", 36))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void birthday(String name, List<Birthday.Person> people, String who, List<Birthday.Person> want) {
List<Birthday.Person> before = new ArrayList<>(people);
assertEquals(want, Birthday.birthday(people, who));
assertEquals(before, people);
}
@Test
void equalityAndPrinting() {
assertEquals(p("Ada", 36), p("Ada", 36));
assertNotEquals(p("Ada", 36), p("Ada", 37));
assertEquals("Person[name=Ada, age=36]", p("Ada", 36).toString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#include "birthday.h"
#include <string.h>
void birthday(const struct person *people, size_t n, const char *name, struct person *out) {
for (size_t i = 0; i < n; i++) {
out[i] = people[i]; // struct assignment copies every member
if (strcmp(out[i].name, name) == 0) {
out[i].age++;
}
}
}
birthday.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
#include <stddef.h>
struct person {
const char *name; // not owned; the caller keeps the text alive
int age;
};
// birthday copies the n people to out. Each person whose name is equal to
// name, byte for byte, is one year older in out. out must have room for n
// people. The input does not change.
void birthday(const struct person *people, size_t n, const char *name, struct person *out);
#endif
test_birthday.c 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
#include "birthday.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty array has a dummy item in it, because C has no empty array. The
// count gives the real length.
#define CHECK(label, cnt, in, who, ...) \
do { \
const struct person people[] = in; \
const struct person want[] = {__VA_ARGS__}; \
struct person before[sizeof people / sizeof people[0]]; \
struct person out[sizeof people / sizeof people[0]]; \
const size_t n = cnt; \
memcpy(before, people, sizeof people); \
birthday(people, n, who, out); \
int ok = 1; \
for (size_t i = 0; ok && i < n; i++) { \
ok = strcmp(out[i].name, want[i].name) == 0 && \
out[i].age == want[i].age && \
people[i].age == before[i].age; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", label); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("first", 2, L({"Ada", 36}, {"Alan", 41}), "Ada", {"Ada", 37}, {"Alan", 41});
CHECK("second", 2, L({"Ada", 36}, {"Alan", 41}), "Alan", {"Ada", 36}, {"Alan", 42});
CHECK("empty", 0, L({"", 0}), "Ada", {"", 0});
CHECK("not-found", 1, L({"Ada", 36}), "Grace", {"Ada", 36});
CHECK("duplicate-name", 3, L({"Ada", 36}, {"Alan", 41}, {"Ada", 9}), "Ada", {"Ada", 37}, {"Alan", 41}, {"Ada", 10});
CHECK("zero-age", 1, L({"Baby", 0}), "Baby", {"Baby", 1});
CHECK("non-ascii", 2, L({"Zo\xc3\xab", 20}, {"Zoe", 30}), "Zo\xc3\xab", {"Zo\xc3\xab", 21}, {"Zoe", 30});
CHECK("case", 1, L({"ada", 36}), "Ada", {"ada", 36});
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
using System.Collections.Generic;
using System.Linq;
// A positional record gets init-only properties, value equality and a
// ToString that prints the properties.
public sealed record Person(string Name, int Age);
public static class Birthday
{
// Returns a new list where each person called name is one year older. The
// with expression copies the record and changes one property.
public static List<Person> Apply(IEnumerable<Person> people, string name) =>
people.Select(p => p.Name == name ? p with { Age = p.Age + 1 } : p).ToList();
}
BirthdayTests.cs 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
using System.Linq;
using Xunit;
public sealed class BirthdayTests
{
public static TheoryData<string, string[], int[], string, int[]> Cases => new()
{
{ "first", new[] { "Ada", "Alan" }, new[] { 36, 41 }, "Ada", new[] { 37, 41 } },
{ "second", new[] { "Ada", "Alan" }, new[] { 36, 41 }, "Alan", new[] { 36, 42 } },
{ "empty", new string[0], new int[0], "Ada", new int[0] },
{ "not-found", new[] { "Ada" }, new[] { 36 }, "Grace", new[] { 36 } },
{ "duplicate-name", new[] { "Ada", "Alan", "Ada" }, new[] { 36, 41, 9 }, "Ada", new[] { 37, 41, 10 } },
{ "zero-age", new[] { "Baby" }, new[] { 0 }, "Baby", new[] { 1 } },
{ "non-ascii", new[] { "Zoë", "Zoe" }, new[] { 20, 30 }, "Zoë", new[] { 21, 30 } },
{ "case", new[] { "ada" }, new[] { 36 }, "Ada", new[] { 36 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] names, int[] ages, string who, int[] wantAges)
{
Assert.NotNull(name);
var people = names.Zip(ages, (n, a) => new Person(n, a)).ToList();
var before = people.ToList();
var got = Birthday.Apply(people, who);
Assert.Equal(names, got.Select(p => p.Name));
Assert.Equal(wantAges, got.Select(p => p.Age));
Assert.Equal(before, people);
}
[Fact]
public void EqualityAndPrinting()
{
Assert.Equal(new Person("Ada", 36), new Person("Ada", 36));
Assert.NotEqual(new Person("Ada", 36), new Person("Ada", 37));
Assert.Equal("Person { Name = Ada, Age = 36 }", new Person("Ada", 36).ToString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
// makePerson builds a frozen object, so its fields cannot change.
export function makePerson(name, age) {
return Object.freeze({ name, age });
}
// birthday returns a new array where each person called name is one year
// older. The spread copies the other fields into a new object.
export function birthday(people, name) {
return people.map((p) => (p.name === name ? Object.freeze({ ...p, age: p.age + 1 }) : p));
}
birthday.test.js 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { birthday, makePerson } from "./birthday.js";
const cases = [
["first", [["Ada", 36], ["Alan", 41]], "Ada", [["Ada", 37], ["Alan", 41]]],
["second", [["Ada", 36], ["Alan", 41]], "Alan", [["Ada", 36], ["Alan", 42]]],
["empty", [], "Ada", []],
["not-found", [["Ada", 36]], "Grace", [["Ada", 36]]],
["duplicate-name", [["Ada", 36], ["Alan", 41], ["Ada", 9]], "Ada", [["Ada", 37], ["Alan", 41], ["Ada", 10]]],
["zero-age", [["Baby", 0]], "Baby", [["Baby", 1]]],
["non-ascii", [["Zoë", 20], ["Zoe", 30]], "Zoë", [["Zoë", 21], ["Zoe", 30]]],
["case", [["ada", 36]], "Ada", [["ada", 36]]],
];
for (const [name, pairs, who, want] of cases) {
test(name, () => {
const people = pairs.map(([n, a]) => makePerson(n, a));
const before = JSON.stringify(people);
const got = birthday(people, who);
assert.deepEqual(got.map((p) => [p.name, p.age]), want);
assert.equal(JSON.stringify(people), before);
});
}
test("equality is by reference", () => {
assert.notEqual(makePerson("Ada", 36), makePerson("Ada", 36));
assert.deepEqual(makePerson("Ada", 36), makePerson("Ada", 36));
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
// readonly fields cannot be assigned after the object is built. The check
// is at compile time only.
export type Person = { readonly name: string; readonly age: number };
export function birthday(people: readonly Person[], name: string): Person[] {
return people.map((p) => (p.name === name ? { ...p, age: p.age + 1 } : p));
}
birthday.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { birthday, type Person } from "./birthday.ts";
const cases: [string, [string, number][], string, [string, number][]][] = [
["first", [["Ada", 36], ["Alan", 41]], "Ada", [["Ada", 37], ["Alan", 41]]],
["second", [["Ada", 36], ["Alan", 41]], "Alan", [["Ada", 36], ["Alan", 42]]],
["empty", [], "Ada", []],
["not-found", [["Ada", 36]], "Grace", [["Ada", 36]]],
["duplicate-name", [["Ada", 36], ["Alan", 41], ["Ada", 9]], "Ada", [["Ada", 37], ["Alan", 41], ["Ada", 10]]],
["zero-age", [["Baby", 0]], "Baby", [["Baby", 1]]],
["non-ascii", [["Zoë", 20], ["Zoe", 30]], "Zoë", [["Zoë", 21], ["Zoe", 30]]],
["case", [["ada", 36]], "Ada", [["ada", 36]]],
];
for (const [name, pairs, who, want] of cases) {
test(name, () => {
const people: Person[] = pairs.map(([n, a]) => ({ name: n, age: a }));
const before = JSON.stringify(people);
const got = birthday(people, who);
assert.deepEqual(got.map((p) => [p.name, p.age]), want);
assert.equal(JSON.stringify(people), before);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
// Package birthday defines a record type as a Go struct.
package birthday
// Person is a struct. Assignment copies all its fields, and == compares them.
type Person struct {
Name string
Age int
}
// Birthday returns a new slice where each person called name is one year older.
func Birthday(people []Person, name string) []Person {
out := make([]Person, len(people))
for i, p := range people {
if p.Name == name {
p.Age++ // p is a copy, so people[i] does not change
}
out[i] = p
}
return out
}
birthday_test.go 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
package birthday
import (
"fmt"
"slices"
"testing"
)
var cases = []struct {
name string
people []Person
who string
want []Person
}{
{"first", []Person{{"Ada", 36}, {"Alan", 41}}, "Ada", []Person{{"Ada", 37}, {"Alan", 41}}},
{"second", []Person{{"Ada", 36}, {"Alan", 41}}, "Alan", []Person{{"Ada", 36}, {"Alan", 42}}},
{"empty", []Person{}, "Ada", []Person{}},
{"not-found", []Person{{"Ada", 36}}, "Grace", []Person{{"Ada", 36}}},
{"duplicate-name", []Person{{"Ada", 36}, {"Alan", 41}, {"Ada", 9}}, "Ada", []Person{{"Ada", 37}, {"Alan", 41}, {"Ada", 10}}},
{"zero-age", []Person{{"Baby", 0}}, "Baby", []Person{{"Baby", 1}}},
{"non-ascii", []Person{{"Zoë", 20}, {"Zoe", 30}}, "Zoë", []Person{{"Zoë", 21}, {"Zoe", 30}}},
{"case", []Person{{"ada", 36}}, "Ada", []Person{{"ada", 36}}},
}
func TestBirthday(t *testing.T) {
for _, c := range cases {
before := slices.Clone(c.people)
if got := Birthday(c.people, c.who); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if !slices.Equal(c.people, before) {
t.Errorf("%s: the input changed", c.name)
}
}
}
func TestEqualityAndPrinting(t *testing.T) {
if (Person{"Ada", 36}) != (Person{"Ada", 36}) {
t.Error("equal fields must give equal structs")
}
if got := fmt.Sprintf("%+v", Person{"Ada", 36}); got != "{Name:Ada Age:36}" {
t.Errorf("got %q", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
/// A struct with named fields. The derives add clone, debug printing and
/// field-by-field equality.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Person {
pub name: String,
pub age: u32,
}
/// Returns a new vector where each person called name is one year older.
pub fn birthday(people: &[Person], name: &str) -> Vec<Person> {
people
.iter()
.map(|p| {
if p.name == name {
// Struct update syntax: the fields not named here come from p.
Person { age: p.age + 1, ..p.clone() }
} else {
p.clone()
}
})
.collect()
}
tests/birthday_test.rs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-record-type/.
use algo_define_a_record_type::{Person, birthday};
fn people(v: &[(&str, u32)]) -> Vec<Person> {
v.iter().map(|&(name, age)| Person { name: name.to_string(), age }).collect()
}
#[test]
fn cases() {
let cases: Vec<(&str, Vec<(&str, u32)>, &str, Vec<(&str, u32)>)> = vec![
("first", vec![("Ada", 36), ("Alan", 41)], "Ada", vec![("Ada", 37), ("Alan", 41)]),
("second", vec![("Ada", 36), ("Alan", 41)], "Alan", vec![("Ada", 36), ("Alan", 42)]),
("empty", vec![], "Ada", vec![]),
("not-found", vec![("Ada", 36)], "Grace", vec![("Ada", 36)]),
("duplicate-name", vec![("Ada", 36), ("Alan", 41), ("Ada", 9)], "Ada", vec![("Ada", 37), ("Alan", 41), ("Ada", 10)]),
("zero-age", vec![("Baby", 0)], "Baby", vec![("Baby", 1)]),
("non-ascii", vec![("Zoë", 20), ("Zoe", 30)], "Zoë", vec![("Zoë", 21), ("Zoe", 30)]),
("case", vec![("ada", 36)], "Ada", vec![("ada", 36)]),
];
for (name, input, who, want) in cases {
let input = people(&input);
let before = input.clone();
assert_eq!(birthday(&input, who), people(&want), "case {name}");
assert_eq!(input, before, "case {name}: the input changed");
}
}
#[test]
fn equality_and_printing() {
let a = Person { name: "Ada".to_string(), age: 36 };
assert_eq!(a, a.clone());
assert_ne!(a, Person { age: 37, ..a.clone() });
assert_eq!(format!("{a:?}"), r#"Person { name: "Ada", age: 36 }"#);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-record-type/.
# birthday NAME PERSON...
# Each PERSON is the text "name|age". Prints one line "name|age" for each
# person, in the same order. Each person whose name is equal to NAME is one
# year older.
birthday() {
# Bash has no record type, so a record is one string with a separator.
# The | must not be in a name.
local who=$1 p name age
shift
for p in "$@"; do
name=${p%|*}
age=${p##*|}
if [[ $name == "$who" ]]; then
age=$((age + 1))
fi
printf '%s|%s\n' "$name" "$age"
done
}
test_birthday.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-record-type/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/birthday.sh"
}
check() { # check WANT NAME PERSON...
local want got
# %b turns each \n in WANT into a newline. The x keeps the trailing
# newlines, which $(...) removes.
want=$(printf '%b' "$1"; printf x)
shift
got=$(birthday "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "first" { check "Ada|37\nAlan|41\n" Ada 'Ada|36' 'Alan|41'; }
@test "second" { check "Ada|36\nAlan|42\n" Alan 'Ada|36' 'Alan|41'; }
@test "empty" { check "" Ada; }
@test "not-found" { check "Ada|36\n" Grace 'Ada|36'; }
@test "duplicate-name" { check "Ada|37\nAlan|41\nAda|10\n" Ada 'Ada|36' 'Alan|41' 'Ada|9'; }
@test "zero-age" { check "Baby|1\n" Baby 'Baby|0'; }
@test "non-ascii" { check "Zoë|21\nZoe|30\n" Zoë 'Zoë|20' 'Zoe|30'; }
@test "case" { check "ada|36\n" Ada 'ada|36'; }
References
- The Python Standard Library, dataclasses, Module contents; replace(); Mutable default values
- Java SE 27 API, Class Record, Class description
- C# reference, Records, Nondestructive mutation; Built-in formatting for display
- The Rust Programming Language, Appendix C, Derivable Traits, Debug for Programmer Output; PartialEq and Eq for Equality Comparisons
- TypeScript Handbook, Object Types, readonly Properties
- The Rust Programming Language, 5.1 Defining and Instantiating Structs, Creating Instances with Struct Update Syntax
- MDN Web Docs, Spread syntax, Spread in object literals
- The Go Programming Language Specification, Struct types; Comparison operators; Slice types
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.5.16.1 Simple assignment; 6.5.9 Equality operators
- cppreference.com, Default comparisons, Equality comparison
- Bash Reference Manual, 3.5.7 Word Splitting; 6.7 Arrays
- MDN Web Docs, Object.freeze(), What is shallow freeze?
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 (bash) | I0 not checked yet |
|
| 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 8HNCXT Edit this page History Report an error Markdown