Taskcore
Use an enum with data
Also called enum with associated values, tagged union, discriminated union, sealed class hierarchy, variant type, sum type example.
Define a shape type whose variants carry different data, build a value from a kind and a list of sides, and match on the variant to get the perimeter, in each tier 1 language.
- Evidence
- Code in 10 languages
Task
Define a type Shape with three variants, each with its own data: a square has one side, a rectangle has a width and a height, and a triangle has three sides. The function perimeter(kind, sides) builds a shape from a kind name and a list of side lengths, then matches on the variant to compute the perimeter. For example, perimeter("rectangle", [2, 5]) is 14. If the data is not a valid shape, the result is no value (None, null, an empty optional or a false flag).
The data is valid when the kind is square with 1 side, rectangle with 2 sides or triangle with 3 sides, every side is greater than 0, and for a triangle each side is less than the sum of the other two. The kind is case-sensitive.
An Enumeration has a fixed set of plain values (see Define an enumeration). An enum with data is a sum type: each variant is a small record. Its type makes illegal combinations, such as a square with two sides, impossible to build (see Make illegal states unrepresentable).
Solutions
| Language | Shape type | Match |
|---|---|---|
| Python | three frozen dataclasses and type Shape = Square | Rectangle | Triangle |
match with class patterns |
| JavaScript | frozen objects with a kind field |
switch on kind, with a default that throws |
| TypeScript | a discriminated union on kind |
switch on kind, with a never check |
| Java | sealed interface Shape and three records |
switch with record patterns and no default |
| C# | an abstract record with a private constructor and three nested sealed records | a switch expression with positional patterns |
| Go | an interface with an unexported method, and three structs | a type switch |
| Rust | enum Shape with struct variants |
match |
| C | a tagged union: an enum tag and a union of structs |
switch on the tag |
| C++ | std::variant<Square, Rectangle, Triangle> |
std::visit with one lambda for each alternative |
| Bash | the string kind side... |
case on the kind |
- Variants with different data. In Rust, an enum variant can carry data, and "Each variant can have different types and amounts of associated data."1 Swift has the same feature: "You can define Swift enumerations to store associated values of any given type, and the value types can be different for each case of the enumeration if needed."2 Kotlin uses sealed classes: "All direct subclasses of a sealed class are known at compile time."3
- The compiler checks the match. "Matches in Rust are exhaustive: We must exhaust every last possibility in order for the code to be valid."4 The Rust solution has no catch-all arm, so a new variant makes every
matchonShapefail to compile until it handles the variant. Kotlin says: "When you combine sealed classes and interfaces with the when expression, you can cover the behavior of all possible subclasses".3 - Java seals the interface. "Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them."5 A
switchwhose case patterns cover every permitted subtype of a sealed interface is exhaustive, so it needs nodefault.6 - TypeScript narrows on a tag. "When every type in a union contains a common property with literal types, TypeScript considers that to be a discriminated union, and can narrow out the members of the union."7 The
defaultbranch assigns the shape to a variable of typenever. This is valid only when every member is handled, so "Adding a new member to the Shape union, will cause a TypeScript error".7 JavaScript has no such check, so itsdefaultbranch throws at run time. - Python matches classes. Class patterns can "use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses)".8 Python does not check that the cases are complete: "If no case matches, none of the branches is executed."8 The solution uses a type union so that a type checker can check the cases, but the interpreter does not.
- C# uses records today. In most cases, the compiler of C# "generates a warning if a switch expression doesn't handle all possible input values."9 The compiler does not know that the nested records are the only subtypes, so the solution has a discard arm that throws. "C# 15 introduces union types, which represent a value that can be one of several case types."10 For a union, "The compiler ensures that switch expressions cover all case types."11 The solution uses records so that it also builds with older compilers.
- Go has no variant types. The Go FAQ says: "We considered adding variant types to Go, but after discussion decided to leave them out because they overlap in confusing ways with interfaces." Instead, "The error example is easy to express using an interface value to hold the error and a type switch to discriminate cases."12 The unexported method
isShapekeeps other packages from adding a variant. The compiler does not check that the type switch has every case. - C pairs a tag with a union. The
kindfield tells which member of the union holds the data. The compiler does not check this: the program must read only the member that the tag names.13 - C++ uses
std::variant. "The class template std::variant represents a type-safe union."14std::visit"Applies the visitor v (a Callable that can be called with any combination of types from Variants) to the Variants values".15 The visitor must accept every alternative, so a missing lambda is a compile error. - Bash uses a string. Bash has no types other than strings and arrays. The solution keeps a shape as words in a string, and
caseselects the code for each kind.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
unknown-kind:circleis not one of the three kinds.wrong-case:Squareis notsquare.too-few-sides,too-many-sidesandno-sides: the number of sides must match the kind.zero-sideandnegative-side: every side must be greater than 0.not-a-triangle: the sides 1, 2 and 3 do not make a triangle, because 3 is not less than 1 + 2.largest: three sides of 1000000 give 3000000, which fits in a 32-bit integer.
Pitfalls
- Python a missing case returns
None. "If no case matches, none of the branches is executed."8 A function that does not handle a new variant ends without areturnand givesNone. Add a lastcase _:that raises an error.
from dataclasses import dataclass
@dataclass(frozen=True)
class Square:
side: int
@dataclass(frozen=True)
class Triangle:
a: int
b: int
c: int
def perimeter(shape):
match shape:
case Square(side):
return 4 * side
# no case for Triangle: the function ends here
print(perimeter(Square(3)))
print(perimeter(Triangle(3, 4, 5)))
12
None
- JavaScript a wrong tag matches no case. A misspelled
kind, hereRectanglein place ofrectangle, matches nocase. The function returnsundefined, and a sum that uses it becomesNaN. Add adefaultthat throws, as the solution does.
function perimeter(shape) {
switch (shape.kind) {
case "square":
return 4 * shape.side;
case "rectangle":
return 2 * (shape.width + shape.height);
}
}
const shapes = [
{ kind: "square", side: 3 },
{ kind: "Rectangle", width: 2, height: 5 },
];
const total = shapes.reduce((sum, s) => sum + perimeter(s), 0);
console.log(perimeter(shapes[1]), total);
undefined NaN
- Go a pointer is another variant. The method set of a pointer type
*Tincludes the methods ofT, so*Squarealso implementsShape.16 A type switch matches "actual types T against the dynamic type of the expression"16, and*Squareis notSquare. Use one form for each variant, and make thedefaultcase report the type.
package main
import "fmt"
type Shape interface{ isShape() }
type Square struct{ Side int }
func (Square) isShape() {}
func perimeter(s Shape) (int, error) {
switch s := s.(type) {
case Square:
return 4 * s.Side, nil
default:
return 0, fmt.Errorf("unknown shape %T", s)
}
}
func main() {
fmt.Println(perimeter(Square{3}))
fmt.Println(perimeter(&Square{3})) // a *Square is also a Shape
}
12 <nil>
0 unknown shape *main.Square
- Rust a catch-all arm hides a new variant. A
_arm "will match all values not specifically listed".4 It makes the match exhaustive, so the compiler accepts it, also after someone adds a variant. Here the arm was written whenShapehad two variants, and a triangle now gets the perimeter 0. List the variants, and do not use_for an enum that can grow.
#[allow(dead_code)]
enum Shape {
Square { side: i64 },
Rectangle { width: i64, height: i64 },
Triangle { a: i64, b: i64, c: i64 }, // added later
}
fn perimeter(shape: &Shape) -> i64 {
match shape {
Shape::Square { side } => 4 * side,
Shape::Rectangle { width, height } => 2 * (width + height),
_ => 0, // written when there were two variants
}
}
fn main() {
let shapes = [
Shape::Square { side: 3 },
Shape::Rectangle { width: 2, height: 5 },
Shape::Triangle { a: 3, b: 4, c: 5 },
];
for s in &shapes {
println!("{}", perimeter(s));
}
}
12
14
0
- C the tag and the data can disagree. Nothing ties the tag to the member that holds the data. "If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type".13 Here a bug changes the tag, and the program reads the side of the square as the width of a rectangle. The other bytes of the union "take unspecified values"13, so the height must not be read at all. Set the tag and the data in one function, as
make_shapedoes.
#include <stdio.h>
enum shape_kind { SHAPE_SQUARE, SHAPE_RECTANGLE };
struct shape {
enum shape_kind kind;
union {
struct {
int side;
} square;
struct {
int width, height;
} rectangle;
} as;
};
int main(void) {
struct shape s = {.kind = SHAPE_SQUARE, .as.square.side = 3};
s.kind = SHAPE_RECTANGLE; // a bug: the tag changes, the data does not
if (s.kind == SHAPE_RECTANGLE) {
printf("width: %d\n", s.as.rectangle.width);
}
return 0;
}
width: 3
- C++
std::getthrows for the wrong alternative.std::get<T>returns the value when the variant holdsT. "Otherwise, throws std::bad_variant_access."17 Usestd::visit, which calls the right lambda, in place of a guess.
#include <iostream>
#include <variant>
struct Square {
int side;
};
struct Rectangle {
int width, height;
};
int main() {
std::variant<Square, Rectangle> shape = Square{3};
try {
std::cout << std::get<Rectangle>(shape).width << '\n';
} catch (const std::bad_variant_access &) {
std::cout << "bad_variant_access\n";
}
std::cout << std::get<Square>(shape).side << '\n';
}
bad_variant_access
3
- Bash a missing value counts as 0.
readgives an empty value to a name that has no word. In arithmetic, "A shell variable that is null or unset evaluates to 0 when referenced by name in an expression."18 A triangle with two sides then has a perimeter and no error. Check the number of values when the shape is built, asmake_shapedoes.
shape_perimeter() {
local kind a b c
read -r kind a b c <<<"$1"
case "$kind" in
triangle) echo $((a + b + c)) ;;
esac
}
shape_perimeter "triangle 3 4 5"
shape_perimeter "triangle 3 4"
12
7
Related tasks
- Define an enumeration: a type with a fixed set of plain values.
- Define a record type: one variant alone is a record.
- Use a tuple: a variant can carry a tuple, such as the Rust
V4(u8, u8, u8, u8). - Make illegal states unrepresentable: the design practice behind this task.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-an-enum-with-data/.
from dataclasses import dataclass
@dataclass(frozen=True)
class Square:
side: int
@dataclass(frozen=True)
class Rectangle:
width: int
height: int
@dataclass(frozen=True)
class Triangle:
a: int
b: int
c: int
# A union of three classes: a value of Shape is exactly one of them.
type Shape = Square | Rectangle | Triangle
def make_shape(kind: str, sides: list[int]) -> Shape | None:
"""Builds a shape, or returns None when the data is not a valid shape."""
if any(s <= 0 for s in sides):
return None
match kind, sides:
case "square", [side]:
return Square(side)
case "rectangle", [width, height]:
return Rectangle(width, height)
case "triangle", [a, b, c] if a < b + c and b < a + c and c < a + b:
return Triangle(a, b, c)
case _:
return None
def shape_perimeter(shape: Shape) -> int:
match shape:
case Square(side):
return 4 * side
case Rectangle(width, height):
return 2 * (width + height)
case Triangle(a, b, c):
return a + b + c
def perimeter(kind: str, sides: list[int]) -> int | None:
shape = make_shape(kind, sides)
return None if shape is None else shape_perimeter(shape)
test_perimeter.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-an-enum-with-data/.
import pytest
from perimeter import Rectangle, Square, make_shape, perimeter
CASES = {
"square": ("square", [3], 12),
"rectangle": ("rectangle", [2, 5], 14),
"triangle": ("triangle", [3, 4, 5], 12),
"unknown-kind": ("circle", [2], None),
"wrong-case": ("Square", [3], None),
"too-few-sides": ("rectangle", [4], None),
"too-many-sides": ("square", [3, 3], None),
"no-sides": ("triangle", [], None),
"zero-side": ("square", [0], None),
"negative-side": ("rectangle", [-2, 5], None),
"not-a-triangle": ("triangle", [1, 2, 3], None),
"largest": ("triangle", [1000000, 1000000, 1000000], 3000000),
}
@pytest.mark.parametrize("case", CASES)
def test_perimeter(case):
kind, sides, want = CASES[case]
assert perimeter(kind, sides) == want
def test_variants_carry_their_data():
assert make_shape("square", [3]) == Square(3)
assert make_shape("rectangle", [2, 5]) == Rectangle(width=2, height=5)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#include "perimeter.hpp"
#include <algorithm>
namespace {
// overloaded builds one visitor from several lambdas.
template <class... Fs> struct overloaded : Fs... {
using Fs::operator()...;
};
} // namespace
std::optional<Shape> make_shape(std::string_view kind, const std::vector<int> &sides) {
if (std::ranges::any_of(sides, [](int s) { return s <= 0; })) {
return std::nullopt;
}
if (kind == "square" && sides.size() == 1) {
return Square{sides[0]};
}
if (kind == "rectangle" && sides.size() == 2) {
return Rectangle{sides[0], sides[1]};
}
if (kind == "triangle" && sides.size() == 3) {
const int a = sides[0], b = sides[1], c = sides[2];
if (a < b + c && b < a + c && c < a + b) {
return Triangle{a, b, c};
}
}
return std::nullopt;
}
// std::visit calls the lambda for the alternative that the variant holds. A
// missing alternative is a compile error.
int shape_perimeter(const Shape &shape) {
return std::visit(overloaded{
[](const Square &s) { return 4 * s.side; },
[](const Rectangle &r) { return 2 * (r.width + r.height); },
[](const Triangle &t) { return t.a + t.b + t.c; },
},
shape);
}
std::optional<int> perimeter(std::string_view kind, const std::vector<int> &sides) {
if (auto shape = make_shape(kind, sides)) {
return shape_perimeter(*shape);
}
return std::nullopt;
}
perimeter.hpp 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#pragma once
#include <optional>
#include <string_view>
#include <variant>
#include <vector>
struct Square {
int side;
bool operator==(const Square &) const = default;
};
struct Rectangle {
int width, height;
bool operator==(const Rectangle &) const = default;
};
struct Triangle {
int a, b, c;
bool operator==(const Triangle &) const = default;
};
// A std::variant holds exactly one of its alternatives and knows which one.
using Shape = std::variant<Square, Rectangle, Triangle>;
std::optional<Shape> make_shape(std::string_view kind, const std::vector<int> &sides);
int shape_perimeter(const Shape &shape);
std::optional<int> perimeter(std::string_view kind, const std::vector<int> &sides);
test_perimeter.cpp 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#include "perimeter.hpp"
#include <iostream>
#include <optional>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view label, std::string_view kind, const std::vector<int> &sides,
std::optional<int> want) {
if (perimeter(kind, sides) != want) {
std::cerr << "case " << label << " failed\n";
failures++;
}
}
int main() {
check("square", "square", {3}, 12);
check("rectangle", "rectangle", {2, 5}, 14);
check("triangle", "triangle", {3, 4, 5}, 12);
check("unknown-kind", "circle", {2}, std::nullopt);
check("wrong-case", "Square", {3}, std::nullopt);
check("too-few-sides", "rectangle", {4}, std::nullopt);
check("too-many-sides", "square", {3, 3}, std::nullopt);
check("no-sides", "triangle", {}, std::nullopt);
check("zero-side", "square", {0}, std::nullopt);
check("negative-side", "rectangle", {-2, 5}, std::nullopt);
check("not-a-triangle", "triangle", {1, 2, 3}, std::nullopt);
check("largest", "triangle", {1000000, 1000000, 1000000}, 3000000);
if (make_shape("rectangle", {2, 5}) != std::optional<Shape>{Rectangle{2, 5}}) {
std::cerr << "case variant-data 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/use-an-enum-with-data/.
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
final class Perimeter {
private Perimeter() {}
/** A sealed interface lists all of its variants; each record carries its own data. */
sealed interface Shape permits Square, Rectangle, Triangle {}
record Square(int side) implements Shape {}
record Rectangle(int width, int height) implements Shape {}
record Triangle(int a, int b, int c) implements Shape {}
/** Builds a shape, or returns an empty Optional when the data is not a valid shape. */
static Optional<Shape> makeShape(String kind, List<Integer> sides) {
if (sides.stream().anyMatch(s -> s <= 0)) {
return Optional.empty();
}
int n = sides.size();
if (kind.equals("square") && n == 1) {
return Optional.of(new Square(sides.get(0)));
}
if (kind.equals("rectangle") && n == 2) {
return Optional.of(new Rectangle(sides.get(0), sides.get(1)));
}
if (kind.equals("triangle") && n == 3) {
int a = sides.get(0);
int b = sides.get(1);
int c = sides.get(2);
if (a < b + c && b < a + c && c < a + b) {
return Optional.of(new Triangle(a, b, c));
}
}
return Optional.empty();
}
/** The switch needs no default: the compiler knows all variants of Shape. */
static int shapePerimeter(Shape shape) {
return switch (shape) {
case Square(int side) -> 4 * side;
case Rectangle(int width, int height) -> 2 * (width + height);
case Triangle(int a, int b, int c) -> a + b + c;
};
}
static OptionalInt perimeter(String kind, List<Integer> sides) {
return makeShape(kind, sides)
.map(s -> OptionalInt.of(shapePerimeter(s)))
.orElse(OptionalInt.empty());
}
}
PerimeterTest.java 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
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 PerimeterTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("square", "square", List.of(3), OptionalInt.of(12)),
Arguments.of("rectangle", "rectangle", List.of(2, 5), OptionalInt.of(14)),
Arguments.of("triangle", "triangle", List.of(3, 4, 5), OptionalInt.of(12)),
Arguments.of("unknown-kind", "circle", List.of(2), OptionalInt.empty()),
Arguments.of("wrong-case", "Square", List.of(3), OptionalInt.empty()),
Arguments.of("too-few-sides", "rectangle", List.of(4), OptionalInt.empty()),
Arguments.of("too-many-sides", "square", List.of(3, 3), OptionalInt.empty()),
Arguments.of("no-sides", "triangle", List.of(), OptionalInt.empty()),
Arguments.of("zero-side", "square", List.of(0), OptionalInt.empty()),
Arguments.of("negative-side", "rectangle", List.of(-2, 5), OptionalInt.empty()),
Arguments.of("not-a-triangle", "triangle", List.of(1, 2, 3), OptionalInt.empty()),
Arguments.of(
"largest", "triangle", List.of(1000000, 1000000, 1000000), OptionalInt.of(3000000)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void perimeter(String name, String kind, List<Integer> sides, OptionalInt want) {
assertEquals(want, Perimeter.perimeter(kind, sides), name);
}
@Test
void variantsCarryTheirData() {
assertEquals(
Optional.of(new Perimeter.Rectangle(2, 5)), Perimeter.makeShape("rectangle", List.of(2, 5)));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#include "perimeter.h"
#include <string.h>
bool make_shape(const char *kind, const int *sides, size_t n, struct shape *out) {
for (size_t i = 0; i < n; i++) {
if (sides[i] <= 0) {
return false;
}
}
if (strcmp(kind, "square") == 0 && n == 1) {
out->kind = SHAPE_SQUARE;
out->as.square.side = sides[0];
return true;
}
if (strcmp(kind, "rectangle") == 0 && n == 2) {
out->kind = SHAPE_RECTANGLE;
out->as.rectangle.width = sides[0];
out->as.rectangle.height = sides[1];
return true;
}
if (strcmp(kind, "triangle") == 0 && n == 3) {
int a = sides[0], b = sides[1], c = sides[2];
if (a < b + c && b < a + c && c < a + b) {
out->kind = SHAPE_TRIANGLE;
out->as.triangle.a = a;
out->as.triangle.b = b;
out->as.triangle.c = c;
return true;
}
}
return false;
}
int shape_perimeter(const struct shape *s) {
switch (s->kind) {
case SHAPE_SQUARE:
return 4 * s->as.square.side;
case SHAPE_RECTANGLE:
return 2 * (s->as.rectangle.width + s->as.rectangle.height);
case SHAPE_TRIANGLE:
return s->as.triangle.a + s->as.triangle.b + s->as.triangle.c;
}
return -1; // not reached for a valid tag
}
bool perimeter(const char *kind, const int *sides, size_t n, int *out) {
struct shape s;
if (!make_shape(kind, sides, n, &s)) {
return false;
}
*out = shape_perimeter(&s);
return true;
}
perimeter.h 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#ifndef PERIMETER_H
#define PERIMETER_H
#include <stdbool.h>
#include <stddef.h>
// C has no enum with data. A tagged union pairs an enum, the tag, with a
// union that holds the data of the variant. Read only the union member that
// the tag names.
enum shape_kind { SHAPE_SQUARE, SHAPE_RECTANGLE, SHAPE_TRIANGLE };
struct shape {
enum shape_kind kind;
union {
struct {
int side;
} square;
struct {
int width, height;
} rectangle;
struct {
int a, b, c;
} triangle;
} as;
};
// make_shape fills *out and returns true, or returns false when the data is
// not a valid shape.
bool make_shape(const char *kind, const int *sides, size_t n, struct shape *out);
int shape_perimeter(const struct shape *s);
// perimeter stores the perimeter in *out and returns true, or returns false
// when the data is not a valid shape.
bool perimeter(const char *kind, const int *sides, size_t n, int *out);
#endif
test_perimeter.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
#include "perimeter.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *label, const char *kind, const int *sides, size_t n, bool want_ok, int want) {
int got = 0;
bool ok = perimeter(kind, sides, n, &got);
if (ok != want_ok || (ok && got != want)) {
fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
// The last element of each list is a dummy, so that an empty list is valid C.
#define L(...) ((const int[]){__VA_ARGS__ 0})
#define N(...) (sizeof L(__VA_ARGS__) / sizeof(int) - 1)
#define CHECK(label, kind, list, ok, want) check(label, kind, L list, N list, ok, want)
int main(void) {
CHECK("square", "square", (3,), true, 12);
CHECK("rectangle", "rectangle", (2, 5,), true, 14);
CHECK("triangle", "triangle", (3, 4, 5,), true, 12);
CHECK("unknown-kind", "circle", (2,), false, 0);
CHECK("wrong-case", "Square", (3,), false, 0);
CHECK("too-few-sides", "rectangle", (4,), false, 0);
CHECK("too-many-sides", "square", (3, 3,), false, 0);
CHECK("no-sides", "triangle", (), false, 0);
CHECK("zero-side", "square", (0,), false, 0);
CHECK("negative-side", "rectangle", (-2, 5,), false, 0);
CHECK("not-a-triangle", "triangle", (1, 2, 3,), false, 0);
CHECK("largest", "triangle", (1000000, 1000000, 1000000,), true, 3000000);
struct shape s;
if (!make_shape("rectangle", (const int[]){2, 5}, 2, &s) || s.kind != SHAPE_RECTANGLE ||
s.as.rectangle.width != 2 || s.as.rectangle.height != 5) {
fprintf(stderr, "case variant-data 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/use-an-enum-with-data/.
using System.Collections.Generic;
using System.Linq;
// An abstract record with a private constructor: only the nested records
// below can derive from it, so they are all of its variants.
public abstract record Shape
{
private Shape() { }
public sealed record Square(int Side) : Shape;
public sealed record Rectangle(int Width, int Height) : Shape;
public sealed record Triangle(int A, int B, int C) : Shape;
}
public static class Perimeter
{
public static Shape? MakeShape(string kind, IReadOnlyList<int> sides)
{
if (sides.Any(s => s <= 0))
{
return null;
}
return (kind, sides.Count) switch
{
("square", 1) => new Shape.Square(sides[0]),
("rectangle", 2) => new Shape.Rectangle(sides[0], sides[1]),
("triangle", 3) when IsTriangle(sides[0], sides[1], sides[2]) =>
new Shape.Triangle(sides[0], sides[1], sides[2]),
_ => null,
};
}
private static bool IsTriangle(int a, int b, int c) => a < b + c && b < a + c && c < a + b;
// The compiler cannot see that the list of variants is closed, so the
// switch needs a discard arm.
public static int ShapePerimeter(Shape shape) => shape switch
{
Shape.Square(var side) => 4 * side,
Shape.Rectangle(var width, var height) => 2 * (width + height),
Shape.Triangle(var a, var b, var c) => a + b + c,
_ => throw new System.ArgumentException("unknown shape", nameof(shape)),
};
public static int? Of(string kind, IReadOnlyList<int> sides) =>
MakeShape(kind, sides) is { } shape ? ShapePerimeter(shape) : null;
}
PerimeterTests.cs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
using Xunit;
public sealed class PerimeterTests
{
public static TheoryData<string, string, int[], int?> Cases => new()
{
{ "square", "square", new[] { 3 }, 12 },
{ "rectangle", "rectangle", new[] { 2, 5 }, 14 },
{ "triangle", "triangle", new[] { 3, 4, 5 }, 12 },
{ "unknown-kind", "circle", new[] { 2 }, null },
{ "wrong-case", "Square", new[] { 3 }, null },
{ "too-few-sides", "rectangle", new[] { 4 }, null },
{ "too-many-sides", "square", new[] { 3, 3 }, null },
{ "no-sides", "triangle", new int[0], null },
{ "zero-side", "square", new[] { 0 }, null },
{ "negative-side", "rectangle", new[] { -2, 5 }, null },
{ "not-a-triangle", "triangle", new[] { 1, 2, 3 }, null },
{ "largest", "triangle", new[] { 1000000, 1000000, 1000000 }, 3000000 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string kind, int[] sides, int? want)
{
Assert.NotNull(name);
Assert.Equal(want, Perimeter.Of(kind, sides));
}
[Fact]
public void VariantsCarryTheirData()
{
Assert.Equal(new Shape.Rectangle(2, 5), Perimeter.MakeShape("rectangle", new[] { 2, 5 }));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
// JavaScript has no enum with data. Each shape is a frozen object with a
// kind field that tells which other fields it has.
export function makeShape(kind, sides) {
if (sides.some((s) => s <= 0)) return null;
if (kind === "square" && sides.length === 1) {
return Object.freeze({ kind, side: sides[0] });
}
if (kind === "rectangle" && sides.length === 2) {
return Object.freeze({ kind, width: sides[0], height: sides[1] });
}
if (kind === "triangle" && sides.length === 3) {
const [a, b, c] = sides;
if (a < b + c && b < a + c && c < a + b) {
return Object.freeze({ kind, a, b, c });
}
}
return null;
}
export function shapePerimeter(shape) {
switch (shape.kind) {
case "square":
return 4 * shape.side;
case "rectangle":
return 2 * (shape.width + shape.height);
case "triangle":
return shape.a + shape.b + shape.c;
default:
throw new TypeError(`not a shape: ${shape.kind}`);
}
}
export function perimeter(kind, sides) {
const shape = makeShape(kind, sides);
return shape === null ? null : shapePerimeter(shape);
}
perimeter.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { makeShape, perimeter, shapePerimeter } from "./perimeter.js";
const cases = [
["square", "square", [3], 12],
["rectangle", "rectangle", [2, 5], 14],
["triangle", "triangle", [3, 4, 5], 12],
["unknown-kind", "circle", [2], null],
["wrong-case", "Square", [3], null],
["too-few-sides", "rectangle", [4], null],
["too-many-sides", "square", [3, 3], null],
["no-sides", "triangle", [], null],
["zero-side", "square", [0], null],
["negative-side", "rectangle", [-2, 5], null],
["not-a-triangle", "triangle", [1, 2, 3], null],
["largest", "triangle", [1000000, 1000000, 1000000], 3000000],
];
for (const [name, kind, sides, want] of cases) {
test(name, () => {
assert.equal(perimeter(kind, sides), want);
});
}
test("variants carry their data", () => {
assert.deepEqual(makeShape("rectangle", [2, 5]), { kind: "rectangle", width: 2, height: 5 });
assert.throws(() => shapePerimeter({ kind: "circle", radius: 1 }), TypeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
// A discriminated union: the kind field tells which variant a value is, and
// each variant has its own fields.
export type Shape =
| { readonly kind: "square"; readonly side: number }
| { readonly kind: "rectangle"; readonly width: number; readonly height: number }
| { readonly kind: "triangle"; readonly a: number; readonly b: number; readonly c: number };
export function makeShape(kind: string, sides: readonly number[]): Shape | null {
if (sides.some((s) => s <= 0)) return null;
if (kind === "square" && sides.length === 1) {
return { kind, side: sides[0] };
}
if (kind === "rectangle" && sides.length === 2) {
return { kind, width: sides[0], height: sides[1] };
}
if (kind === "triangle" && sides.length === 3) {
const [a, b, c] = sides;
if (a < b + c && b < a + c && c < a + b) return { kind, a, b, c };
}
return null;
}
export function shapePerimeter(shape: Shape): number {
switch (shape.kind) {
case "square":
return 4 * shape.side;
case "rectangle":
return 2 * (shape.width + shape.height);
case "triangle":
return shape.a + shape.b + shape.c;
default: {
// Every variant is handled, so shape has the type never here.
const unreachable: never = shape;
return unreachable;
}
}
}
export function perimeter(kind: string, sides: readonly number[]): number | null {
const shape = makeShape(kind, sides);
return shape === null ? null : shapePerimeter(shape);
}
perimeter.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { makeShape, perimeter } from "./perimeter.ts";
const cases: [string, string, number[], number | null][] = [
["square", "square", [3], 12],
["rectangle", "rectangle", [2, 5], 14],
["triangle", "triangle", [3, 4, 5], 12],
["unknown-kind", "circle", [2], null],
["wrong-case", "Square", [3], null],
["too-few-sides", "rectangle", [4], null],
["too-many-sides", "square", [3, 3], null],
["no-sides", "triangle", [], null],
["zero-side", "square", [0], null],
["negative-side", "rectangle", [-2, 5], null],
["not-a-triangle", "triangle", [1, 2, 3], null],
["largest", "triangle", [1000000, 1000000, 1000000], 3000000],
];
for (const [name, kind, sides, want] of cases) {
test(name, () => {
assert.equal(perimeter(kind, sides), want);
});
}
test("variants carry their data", () => {
assert.deepEqual(makeShape("triangle", [3, 4, 5]), { kind: "triangle", a: 3, b: 4, c: 5 });
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
// Package shape builds a value of one of three shape types and matches on it.
package shape
// Shape is a closed set of types: the method isShape is not exported, so
// only this package can add a variant.
type Shape interface{ isShape() }
type Square struct{ Side int }
type Rectangle struct{ Width, Height int }
type Triangle struct{ A, B, C int }
func (Square) isShape() {}
func (Rectangle) isShape() {}
func (Triangle) isShape() {}
// MakeShape returns the shape, or false when the data is not a valid shape.
func MakeShape(kind string, sides []int) (Shape, bool) {
for _, s := range sides {
if s <= 0 {
return nil, false
}
}
switch {
case kind == "square" && len(sides) == 1:
return Square{sides[0]}, true
case kind == "rectangle" && len(sides) == 2:
return Rectangle{sides[0], sides[1]}, true
case kind == "triangle" && len(sides) == 3:
a, b, c := sides[0], sides[1], sides[2]
if a < b+c && b < a+c && c < a+b {
return Triangle{a, b, c}, true
}
}
return nil, false
}
// ShapePerimeter uses a type switch. The compiler does not check that every
// variant has a case, so the default case panics.
func ShapePerimeter(s Shape) int {
switch s := s.(type) {
case Square:
return 4 * s.Side
case Rectangle:
return 2 * (s.Width + s.Height)
case Triangle:
return s.A + s.B + s.C
default:
panic("unknown shape")
}
}
// Perimeter returns the perimeter, or false when the data is not a valid shape.
func Perimeter(kind string, sides []int) (int, bool) {
s, ok := MakeShape(kind, sides)
if !ok {
return 0, false
}
return ShapePerimeter(s), true
}
perimeter_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
package shape
import "testing"
var cases = []struct {
name string
kind string
sides []int
want int
wantOK bool
}{
{"square", "square", []int{3}, 12, true},
{"rectangle", "rectangle", []int{2, 5}, 14, true},
{"triangle", "triangle", []int{3, 4, 5}, 12, true},
{"unknown-kind", "circle", []int{2}, 0, false},
{"wrong-case", "Square", []int{3}, 0, false},
{"too-few-sides", "rectangle", []int{4}, 0, false},
{"too-many-sides", "square", []int{3, 3}, 0, false},
{"no-sides", "triangle", []int{}, 0, false},
{"zero-side", "square", []int{0}, 0, false},
{"negative-side", "rectangle", []int{-2, 5}, 0, false},
{"not-a-triangle", "triangle", []int{1, 2, 3}, 0, false},
{"largest", "triangle", []int{1000000, 1000000, 1000000}, 3000000, true},
}
func TestPerimeter(t *testing.T) {
for _, c := range cases {
got, ok := Perimeter(c.kind, c.sides)
if got != c.want || ok != c.wantOK {
t.Errorf("%s: got (%d, %v), want (%d, %v)", c.name, got, ok, c.want, c.wantOK)
}
}
}
func TestVariantsCarryTheirData(t *testing.T) {
s, _ := MakeShape("rectangle", []int{2, 5})
if r, ok := s.(Rectangle); !ok || r != (Rectangle{2, 5}) {
t.Errorf("got %#v", s)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
/// An enum whose variants carry different data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
Square { side: i64 },
Rectangle { width: i64, height: i64 },
Triangle { a: i64, b: i64, c: i64 },
}
/// Builds a shape, or returns None when the data is not a valid shape.
pub fn make_shape(kind: &str, sides: &[i64]) -> Option<Shape> {
if sides.iter().any(|&s| s <= 0) {
return None;
}
match (kind, sides) {
("square", &[side]) => Some(Shape::Square { side }),
("rectangle", &[width, height]) => Some(Shape::Rectangle { width, height }),
("triangle", &[a, b, c]) if a < b + c && b < a + c && c < a + b => {
Some(Shape::Triangle { a, b, c })
}
_ => None,
}
}
impl Shape {
/// The match must cover every variant, or the program does not compile.
pub fn perimeter(&self) -> i64 {
match *self {
Shape::Square { side } => 4 * side,
Shape::Rectangle { width, height } => 2 * (width + height),
Shape::Triangle { a, b, c } => a + b + c,
}
}
}
pub fn perimeter(kind: &str, sides: &[i64]) -> Option<i64> {
make_shape(kind, sides).map(|s| s.perimeter())
}
tests/perimeter_test.rs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-an-enum-with-data/.
use algo_use_an_enum_with_data::{Shape, make_shape, perimeter};
#[test]
fn cases() {
let cases: Vec<(&str, &str, Vec<i64>, Option<i64>)> = vec![
("square", "square", vec![3], Some(12)),
("rectangle", "rectangle", vec![2, 5], Some(14)),
("triangle", "triangle", vec![3, 4, 5], Some(12)),
("unknown-kind", "circle", vec![2], None),
("wrong-case", "Square", vec![3], None),
("too-few-sides", "rectangle", vec![4], None),
("too-many-sides", "square", vec![3, 3], None),
("no-sides", "triangle", vec![], None),
("zero-side", "square", vec![0], None),
("negative-side", "rectangle", vec![-2, 5], None),
("not-a-triangle", "triangle", vec![1, 2, 3], None),
("largest", "triangle", vec![1000000, 1000000, 1000000], Some(3000000)),
];
for (name, kind, sides, want) in cases {
assert_eq!(perimeter(kind, &sides), want, "case {name}");
}
}
#[test]
fn variants_carry_their_data() {
assert_eq!(
make_shape("rectangle", &[2, 5]),
Some(Shape::Rectangle { width: 2, height: 5 })
);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-an-enum-with-data/.
# Bash has no enum with data. A shape is a string: the kind, then the sides,
# separated by spaces, such as "rectangle 2 5". A case statement on the kind
# plays the part of the match.
# make_shape KIND SIDE...
# Prints the shape string, or returns status 1 when the data is not a valid
# shape.
make_shape() {
local kind=$1 s
shift
for s in "$@"; do
((s > 0)) || return 1
done
case "$kind:$#" in
square:1 | rectangle:2) ;;
triangle:3)
(($1 < $2 + $3 && $2 < $1 + $3 && $3 < $1 + $2)) || return 1
;;
*) return 1 ;;
esac
printf '%s\n' "$kind $*"
}
# shape_perimeter SHAPE
shape_perimeter() {
local kind a b c
read -r kind a b c <<<"$1"
case "$kind" in
square) echo $((4 * a)) ;;
rectangle) echo $((2 * (a + b))) ;;
triangle) echo $((a + b + c)) ;;
*) return 1 ;;
esac
}
# perimeter KIND SIDE...
# Prints the perimeter, or prints nothing and returns status 1.
perimeter() {
local shape
shape=$(make_shape "$@") || return 1
shape_perimeter "$shape"
}
test_perimeter.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-an-enum-with-data/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/perimeter.sh"
}
check() { # check WANT KIND SIDE...; WANT is none for no result
local want=$1 got status=0
shift
got=$(perimeter "$@") || status=$?
if [ "$want" = none ]; then
[ "$status" -ne 0 ] && [ -z "$got" ] || { printf 'got: %s\n' "$got"; return 1; }
else
[ "$status" -eq 0 ] && [ "$got" = "$want" ] || { printf 'got: %s\nwant: %s\n' "$got" "$want"; return 1; }
fi
}
@test "square" { check 12 square 3; }
@test "rectangle" { check 14 rectangle 2 5; }
@test "triangle" { check 12 triangle 3 4 5; }
@test "unknown-kind" { check none circle 2; }
@test "wrong-case" { check none Square 3; }
@test "too-few-sides" { check none rectangle 4; }
@test "too-many-sides" { check none square 3 3; }
@test "no-sides" { check none triangle; }
@test "zero-side" { check none square 0; }
@test "negative-side" { check none rectangle -2 5; }
@test "not-a-triangle" { check none triangle 1 2 3; }
@test "largest" { check 3000000 triangle 1000000 1000000 1000000; }
@test "variants carry their data" { [ "$(make_shape rectangle 2 5)" = "rectangle 2 5" ]; }
References
- The Rust Programming Language, 6.1 Defining an Enum, Enum Values
- The Swift Programming Language, Enumerations, Associated Values
- Kotlin documentation, Sealed classes and interfaces, the introduction
- The Rust Programming Language, 6.2 The match Control Flow Construct, Matches Are Exhaustive; Catch-All Patterns and the _ Placeholder
- JEP 409, Sealed Classes, Summary; Goals
- The Java Language Specification, Java SE 27 Edition, 14.11.1.1 Exhaustive Switch Blocks
- TypeScript Handbook, Narrowing, Discriminated unions; Exhaustiveness checking
- The Python Tutorial, More Control Flow Tools, 4.7 match Statements
- C# reference, switch expression, Nonexhaustive switch expressions
- What's new in C# 15, Union types
- C# reference, Union types, the introduction
- Go FAQ, Why does Go not have variant types?
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.2.6.1 paragraph 7; 6.5.2.3 footnote 95
- cppreference.com, std::variant, the description
- cppreference.com, std::visit, the description
- The Go Programming Language Specification, Method sets; Type switches
- cppreference.com, std::get (std::variant), the description
- Bash Reference Manual, 6.5 Shell Arithmetic
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 3HJCC5 Edit this page History Report an error Markdown