Taskintro
Define an enumeration
Also called define an enum, enum type, enumerated type, list the values of an enum, enum to string, string to enum, enum to int.
Define an enum of the seven weekdays, convert a name to a value and back, and step through the values by their positions, in each tier 1 language.
- Evidence
- Code in 10 languages
Task
Define an enumeration Day with the seven values monday to sunday, in that order. Then use it in the function cycle(start, steps). The function converts the name start to a Day, and returns steps names that begin at that day and go on in the order of the enumeration. After sunday comes monday again. For example, cycle("friday", 4) is ["friday", "saturday", "sunday", "monday"].
A name must be one of the seven names, exactly and in lower case. For any other text, such as "Friday", "funday" or "3", the result is the empty list. steps is from 0 to 100.
The task shows the four things that a program does with an enumeration: it lists the values in order, converts a name to a value, converts a value to its position and back, and converts a value to its name. For the idea behind enumerations, see Enumeration.
Solutions
| Language | Definition | All values in order | Value to position |
|---|---|---|---|
| Python | class Day(Enum) with MONDAY = "monday" |
list(Day) |
the index in list(Day) |
| JavaScript | Object.freeze({ MONDAY: "monday", ... }) |
Object.values(Day) |
indexOf |
| TypeScript | an object with as const, and type Day from its values |
Object.values(Day) |
indexOf |
| Java | enum Day { MONDAY, ... } |
Day.values() |
d.ordinal() |
| C# | enum Day { Monday, ... } |
Enum.GetValues<Day>() |
(int)d |
| Go | type Day int and constants with iota |
a loop from Monday to numDays - 1 |
the value itself |
| Rust | enum Day { Monday, ... } |
a constant array Day::ALL |
d as usize |
| C | enum day { MONDAY, ..., DAY_COUNT } |
a loop from MONDAY to DAY_COUNT - 1 |
the value itself |
| C++ | enum class Day { Monday, ... } |
a loop over 0 to 6 |
static_cast<int>(d) |
| Bash | the indexed array DAYS=(monday ... sunday) |
"${DAYS[@]}" |
the array index |
- Python. An enumeration "is a set of symbolic names (members) bound to unique values"1. The members come in order: iteration "Returns each member in cls in definition order"1.
Day(value)looks up a member by value, andDay[name]looks up a member by name. For a name that is not in the class, the index form "raises a KeyError"1. - Java. Each enum class has a static
values()method. "All the constants of an enum class can be obtained by calling the implicit public static T[] values() method of that class."2 The position comes fromordinal(), which "Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero)."2 The Java API also says: "Most programmers will have no use for this method."2 Do not store an ordinal in a file or a database, because it changes when someone puts a new constant in the middle. - C#. "An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type."3 The members "start with zero and increase by one following the definition text order."3 Casts go both ways: "For any enumeration type, explicit conversions exist between the enumeration type and its underlying integral type."3
- Go. Go has no enum keyword. The solution defines a named integer type and a block of constants: "Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants."4 A
Stringmethod gives the names. The last constantnumDayscounts the days. - Rust. A Rust enum has no built-in list of its variants, so the solution writes the array
Day::ALLand amatchfor the names. The position is a cast: "If an enumeration is unit-only (with no tuple and struct variants), then its discriminant can be directly accessed with a numeric cast"5. There is no cast from an integer to an enum, so the solution indexesDay::ALL. - C. "The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted."6 C keeps no names at run time, so the solution has a table of names with one entry for each constant. The last constant,
DAY_COUNT, is the size of the table. - C++. The solution uses a scoped enumeration,
enum class. "There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator."7 - JavaScript and TypeScript. JavaScript has no enum. A frozen object takes its place, because "A frozen object can no longer be changed"8. TypeScript has an
enumkeyword, but its handbook gives an object withas constas an alternative. Its main reason is that this form "keeps your codebase aligned with the state of JavaScript"9. - Bash. Bash has no enum. An indexed array keeps the names in order, and the index of a name is its value. "Bash provides one-dimensional indexed and associative array variables."10
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
wrap: aftersundaycomesmonday. The solutions use the position modulo 7.zero-steps: 0 steps give an empty list, also for a valid name.more-than-a-week: 9 steps fromsundaygo round the week once and givesundayandmondaytwice.unknown,empty-name: a name that is not a day gives an empty list.wrong-case:"Friday"is not a name. A parse that ignores case, such asvalueOf(start.toUpperCase())in Java, is wrong here.number:"3"is not a name. In C#,Enum.TryParseaccepts it as the value 3 (see Pitfalls).
Pitfalls
- Python an
Enummember is not equal to its value. A member is not a string, so a comparison with the string value is false. Compare with.value, or useStrEnum, which "is the same as Enum , but its members are also strings and can be used in most of the same places that a string can be used."1
from enum import Enum, StrEnum
class Day(Enum):
MONDAY = "monday"
class Day2(StrEnum):
MONDAY = "monday"
print("yes" if Day.MONDAY == "monday" else "no")
print("yes" if Day.MONDAY.value == "monday" else "no")
print("yes" if Day2.MONDAY == "monday" else "no")
no
yes
yes
- JavaScript an object that is not frozen can change. Any code can give a new value to a property of a plain object, so the "enum" changes for the whole program.
Object.freezestops that8. Outside strict mode, a write to a frozen object fails with no error, soReflect.setshows the result:
const Loose = { MONDAY: "monday" };
Loose.MONDAY = "tuesday";
console.log(Loose.MONDAY);
const Day = Object.freeze({ MONDAY: "monday" });
console.log(Reflect.set(Day, "MONDAY", "tuesday") ? "yes" : "no", Day.MONDAY);
tuesday
no monday
- Java
valueOfis case-sensitive. "The name must match exactly an identifier used to declare an enum constant in this class."2 For any other text, it throws an exception and does not return null:
public class Main {
enum Day {
MONDAY,
TUESDAY
}
public static void main(String[] args) {
System.out.println(Day.valueOf("MONDAY"));
try {
Day.valueOf("monday");
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException");
}
}
}
MONDAY
IllegalArgumentException
- C#
Enum.TryParseaccepts any number. "If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type."11 Thus"9"parses to aDaythat is not a day. Check the result withEnum.IsDefined:
using System;
bool ok = Enum.TryParse<Day>("9", out var d);
Console.WriteLine((ok ? "yes" : "no") + " " + d);
Console.WriteLine(Enum.IsDefined(d) ? "yes" : "no");
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
yes 9
no
- Go any integer is a
Day. The constants are integers, and aDaycan hold anyintvalue. The compiler does not check that a value is one of the constants. Check the range before you use the value as an index:
package main
import "fmt"
type Day int
const (
Monday Day = iota
Tuesday
numDays
)
func main() {
var d Day = 9
fmt.Println(int(d))
if d < 0 || d >= numDays {
fmt.Println("not a day")
}
}
9
not a day
- C an enum variable can hold other numbers. "Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type."6 A variable of the type can hold a number that is not one of the constants, and a
switchon it then goes todefault:
#include <stdio.h>
enum day { MONDAY, TUESDAY, DAY_COUNT };
int main(void) {
enum day d = 42;
switch (d) {
case MONDAY:
printf("monday\n");
break;
case TUESDAY:
printf("tuesday\n");
break;
default:
printf("not a day: %d\n", (int)d);
}
return 0;
}
not a day: 42
- C++ an unscoped enum converts to
int. The values of a plainenumtake part in arithmetic and comparisons with numbers with no cast, so a mistake compiles. A scopedenum classneeds astatic_cast7:
#include <iostream>
enum Fruit { apple, pear };
enum class Day { monday, tuesday };
int main() {
int n = pear + 1;
std::cout << n << ' ' << (pear == 1 ? "yes" : "no") << '\n';
std::cout << static_cast<int>(Day::tuesday) + 1 << '\n';
}
2 yes
2
- Bash an index past the end gives empty text. A read of
${DAYS[7]}gives an empty string and no error. A negative index counts from the end: "an index of -1 refers to the last element"10. Use the index modulo the length:
DAYS=(monday tuesday wednesday thursday friday saturday sunday)
echo "[${DAYS[7]}] [${DAYS[-1]}]"
i=6
echo "${DAYS[(i + 1) % ${#DAYS[@]}]}"
[] [sunday]
monday
Related tasks
- Use an enum with data: an enum whose cases carry values.
- Define a record type: a type with named fields.
- Use a tuple: group values by position.
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-an-enumeration/.
from enum import Enum
class Day(Enum):
"""The days of the week, in order. Each value is the name in lower case."""
MONDAY = "monday"
TUESDAY = "tuesday"
WEDNESDAY = "wednesday"
THURSDAY = "thursday"
FRIDAY = "friday"
SATURDAY = "saturday"
SUNDAY = "sunday"
def cycle(start: str, steps: int) -> list[str]:
"""Returns steps day names from start on, with monday after sunday."""
try:
day = Day(start) # from a string: look up the member by value
except ValueError:
return []
days = list(Day) # iteration gives the members in definition order
i = days.index(day) # to an integer: the position
return [days[(i + k) % len(days)].value for k in range(steps)]
test_cycle.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-an-enumeration/.
import pytest
from cycle import Day, cycle
CASES = {
"weekdays": ("monday", 3, ["monday", "tuesday", "wednesday"]),
"wrap": ("friday", 4, ["friday", "saturday", "sunday", "monday"]),
"zero-steps": ("monday", 0, []),
"more-than-a-week": (
"sunday",
9,
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"],
),
"unknown": ("funday", 3, []),
"wrong-case": ("Friday", 2, []),
"number": ("3", 2, []),
"empty-name": ("", 1, []),
}
@pytest.mark.parametrize("case", CASES)
def test_cycle(case):
start, steps, want = CASES[case]
assert cycle(start, steps) == want
def test_members():
assert len(Day) == 7
assert Day["FRIDAY"] is Day.FRIDAY
assert Day.FRIDAY.name == "FRIDAY"
assert Day.FRIDAY.value == "friday"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#include "cycle.hpp"
#include <array>
namespace {
constexpr std::array<std::string_view, day_count> names{"monday", "tuesday", "wednesday", "thursday",
"friday", "saturday", "sunday"};
}
std::string_view to_string(Day d) { return names.at(static_cast<std::size_t>(d)); }
std::optional<Day> parse_day(std::string_view s) {
for (int i = 0; i < day_count; i++) {
if (names[static_cast<std::size_t>(i)] == s) {
return static_cast<Day>(i);
}
}
return std::nullopt;
}
std::vector<std::string> cycle(std::string_view start, int steps) {
std::vector<std::string> out;
auto d = parse_day(start);
if (!d) {
return out;
}
int i = static_cast<int>(*d);
for (int k = 0; k < steps; k++) {
out.emplace_back(to_string(static_cast<Day>((i + k) % day_count)));
}
return out;
}
cycle.hpp 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#pragma once
#include <optional>
#include <string>
#include <string_view>
#include <vector>
// A scoped enumeration: the names are Day::Monday and so on, and a Day does
// not convert to int without a static_cast.
enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
inline constexpr int day_count = 7;
std::string_view to_string(Day d);
std::optional<Day> parse_day(std::string_view s);
// cycle returns steps day names from start on, with monday after sunday.
std::vector<std::string> cycle(std::string_view start, int steps);
test_cycle.cpp 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#include "cycle.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
static int failures = 0;
using Names = std::vector<std::string>;
static void check(std::string_view label, std::string_view start, int steps, const Names &want) {
if (cycle(start, steps) != want) {
std::cerr << "case " << label << " failed\n";
failures++;
}
}
int main() {
check("weekdays", "monday", 3, {"monday", "tuesday", "wednesday"});
check("wrap", "friday", 4, {"friday", "saturday", "sunday", "monday"});
check("zero-steps", "monday", 0, {});
check("more-than-a-week", "sunday", 9,
{"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"});
check("unknown", "funday", 3, {});
check("wrong-case", "Friday", 2, {});
check("number", "3", 2, {});
check("empty-name", "", 1, {});
if (static_cast<int>(Day::Friday) != 4 || to_string(Day::Friday) != "friday" || parse_day("friday") != Day::Friday) {
std::cerr << "case to-and-from 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-an-enumeration/.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
final class Cycle {
private Cycle() {}
/** The days of the week. values() gives them in this order. */
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
String label() {
return name().toLowerCase(Locale.ROOT);
}
}
static List<String> cycle(String start, int steps) {
Day[] days = Day.values();
for (Day d : days) {
if (d.label().equals(start)) {
List<String> out = new ArrayList<>();
for (int k = 0; k < steps; k++) {
out.add(days[(d.ordinal() + k) % days.length].label());
}
return out;
}
}
return List.of();
}
}
CycleTest.java 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
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 CycleTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("weekdays", "monday", 3, List.of("monday", "tuesday", "wednesday")),
Arguments.of("wrap", "friday", 4, List.of("friday", "saturday", "sunday", "monday")),
Arguments.of("zero-steps", "monday", 0, List.of()),
Arguments.of("more-than-a-week", "sunday", 9, List.of("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday")),
Arguments.of("unknown", "funday", 3, List.of()),
Arguments.of("wrong-case", "Friday", 2, List.of()),
Arguments.of("number", "3", 2, List.of()),
Arguments.of("empty-name", "", 1, List.of()));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void cycle(String name, String start, int steps, List<String> want) {
assertEquals(want, Cycle.cycle(start, steps));
}
@Test
void nameAndOrdinal() {
assertEquals("FRIDAY", Cycle.Day.FRIDAY.name());
assertEquals(4, Cycle.Day.FRIDAY.ordinal());
assertEquals(Cycle.Day.FRIDAY, Cycle.Day.valueOf("FRIDAY"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#include "cycle.h"
#include <string.h>
// C keeps no names for enumeration constants at run time, so a table
// holds them.
static const char *const names[DAY_COUNT] = {
[MONDAY] = "monday", [TUESDAY] = "tuesday", [WEDNESDAY] = "wednesday",
[THURSDAY] = "thursday", [FRIDAY] = "friday", [SATURDAY] = "saturday",
[SUNDAY] = "sunday",
};
const char *day_name(enum day d) {
if ((int)d < 0 || d >= DAY_COUNT) {
return NULL;
}
return names[d];
}
size_t cycle(const char *start, size_t steps, const char **out) {
for (int d = MONDAY; d < DAY_COUNT; d++) {
if (strcmp(names[d], start) == 0) {
for (size_t k = 0; k < steps; k++) {
out[k] = day_name((enum day)((d + k) % DAY_COUNT));
}
return steps;
}
}
return 0;
}
cycle.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#ifndef CYCLE_H
#define CYCLE_H
#include <stddef.h>
// The days of the week. The enumeration constants are the ints 0 to 6, and
// DAY_COUNT is 7.
enum day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, DAY_COUNT };
// day_name gives the name of d in lower case, or NULL if d is not a day.
const char *day_name(enum day d);
// cycle writes steps names to out, from the day with the name start on, with
// monday after sunday. out must have room for steps names. It returns the
// number of names: steps, or 0 if start is not a name.
size_t cycle(const char *start, size_t steps, const char **out);
#endif
test_cycle.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
#include "cycle.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *label, const char *start, size_t steps, const char *const *want, size_t want_n) {
const char *out[16];
size_t n = cycle(start, steps, out);
int ok = n == want_n;
for (size_t i = 0; ok && i < n; i++) {
ok = strcmp(out[i], want[i]) == 0;
}
if (!ok) {
fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
#define CHECK(label, start, steps, ...) \
do { \
const char *const want[] = {__VA_ARGS__}; \
check(label, start, steps, want, sizeof want / sizeof want[0] - 1); \
} while (0)
int main(void) {
// Each list of names ends with a dummy "", because C has no empty array.
CHECK("weekdays", "monday", 3, "monday", "tuesday", "wednesday", "");
CHECK("wrap", "friday", 4, "friday", "saturday", "sunday", "monday", "");
CHECK("zero-steps", "monday", 0, "");
CHECK("more-than-a-week", "sunday", 9, "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday", "");
CHECK("unknown", "funday", 3, "");
CHECK("wrong-case", "Friday", 2, "");
CHECK("number", "3", 2, "");
CHECK("empty-name", "", 1, "");
if (FRIDAY != 4 || strcmp(day_name(FRIDAY), "friday") != 0 || day_name((enum day)9) != NULL) {
fprintf(stderr, "case day_name 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-an-enumeration/.
using System;
using System.Collections.Generic;
// An enum whose members have the int values 0 to 6.
public enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
public static class Cycle
{
public static List<string> Of(string start, int steps)
{
var days = Enum.GetValues<Day>();
var result = new List<string>();
foreach (var d in days)
{
// Compare with the names, not Enum.TryParse, which also accepts
// numbers such as "3".
if (d.ToString().ToLowerInvariant() != start)
{
continue;
}
for (int k = 0; k < steps; k++)
{
var next = (Day)(((int)d + k) % days.Length);
result.Add(next.ToString().ToLowerInvariant());
}
break;
}
return result;
}
}
CycleTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
using Xunit;
public sealed class CycleTests
{
public static TheoryData<string, string, int, string[]> Cases => new()
{
{ "weekdays", "monday", 3, new[] { "monday", "tuesday", "wednesday" } },
{ "wrap", "friday", 4, new[] { "friday", "saturday", "sunday", "monday" } },
{ "zero-steps", "monday", 0, new string[0] },
{ "more-than-a-week", "sunday", 9, new[] { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday" } },
{ "unknown", "funday", 3, new string[0] },
{ "wrong-case", "Friday", 2, new string[0] },
{ "number", "3", 2, new string[0] },
{ "empty-name", "", 1, new string[0] },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string start, int steps, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Cycle.Of(start, steps));
}
[Fact]
public void ToAndFromInt()
{
Assert.Equal(4, (int)Day.Friday);
Assert.Equal(Day.Friday, (Day)4);
Assert.Equal("Friday", Day.Friday.ToString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
// JavaScript has no enum. A frozen object maps each name to its value, and
// Object.values gives the values in the order of the definition.
export const Day = Object.freeze({
MONDAY: "monday",
TUESDAY: "tuesday",
WEDNESDAY: "wednesday",
THURSDAY: "thursday",
FRIDAY: "friday",
SATURDAY: "saturday",
SUNDAY: "sunday",
});
const DAYS = Object.values(Day);
export function cycle(start, steps) {
const i = DAYS.indexOf(start);
if (i < 0) return [];
return Array.from({ length: steps }, (_, k) => DAYS[(i + k) % DAYS.length]);
}
cycle.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Day, cycle } from "./cycle.js";
const cases = [
["weekdays", "monday", 3, ["monday", "tuesday", "wednesday"]],
["wrap", "friday", 4, ["friday", "saturday", "sunday", "monday"]],
["zero-steps", "monday", 0, []],
["more-than-a-week", "sunday", 9, ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"]],
["unknown", "funday", 3, []],
["wrong-case", "Friday", 2, []],
["number", "3", 2, []],
["empty-name", "", 1, []],
];
for (const [name, start, steps, want] of cases) {
test(name, () => assert.deepEqual(cycle(start, steps), want));
}
test("the enum object is frozen", () => {
assert.equal(Object.isFrozen(Day), true);
assert.equal(Object.keys(Day).length, 7);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
// An object with "as const" in place of a TypeScript enum. Its values have
// literal types, and the type Day is the union of them.
export const Day = {
Monday: "monday",
Tuesday: "tuesday",
Wednesday: "wednesday",
Thursday: "thursday",
Friday: "friday",
Saturday: "saturday",
Sunday: "sunday",
} as const;
export type Day = (typeof Day)[keyof typeof Day];
const DAYS: readonly Day[] = Object.values(Day);
// isDay converts a string to a Day: after the check, TypeScript knows that s
// is a Day.
function isDay(s: string): s is Day {
return (DAYS as readonly string[]).includes(s);
}
export function cycle(start: string, steps: number): Day[] {
if (!isDay(start)) return [];
const i = DAYS.indexOf(start);
return Array.from({ length: steps }, (_, k) => DAYS[(i + k) % DAYS.length]);
}
cycle.test.ts 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { cycle } from "./cycle.ts";
const cases: [string, string, number, string[]][] = [
["weekdays", "monday", 3, ["monday", "tuesday", "wednesday"]],
["wrap", "friday", 4, ["friday", "saturday", "sunday", "monday"]],
["zero-steps", "monday", 0, []],
["more-than-a-week", "sunday", 9, ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"]],
["unknown", "funday", 3, []],
["wrong-case", "Friday", 2, []],
["number", "3", 2, []],
["empty-name", "", 1, []],
];
for (const [name, start, steps, want] of cases) {
test(name, () => assert.deepEqual(cycle(start, steps), want));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
// Package cycle defines an enumeration with iota.
package cycle
// Day is a day of the week. Go has no enum type; a named integer type and
// a block of constants take its place.
type Day int
const (
Monday Day = iota
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
numDays // the number of days; not a day
)
var names = [numDays]string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
// String gives the name of the day. fmt calls it when it prints a Day.
func (d Day) String() string {
if d < 0 || d >= numDays {
return "Day(?)"
}
return names[d]
}
// Parse gives the day with the name s, or false.
func Parse(s string) (Day, bool) {
for d := Monday; d < numDays; d++ {
if names[d] == s {
return d, true
}
}
return 0, false
}
// Cycle returns steps day names from start on, with monday after sunday.
func Cycle(start string, steps int) []string {
d, ok := Parse(start)
if !ok {
return []string{}
}
out := make([]string, 0, steps)
for k := range steps {
out = append(out, ((d + Day(k)) % numDays).String())
}
return out
}
cycle_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
package cycle
import (
"fmt"
"slices"
"testing"
)
var cases = []struct {
name string
start string
steps int
want []string
}{
{"weekdays", "monday", 3, []string{"monday", "tuesday", "wednesday"}},
{"wrap", "friday", 4, []string{"friday", "saturday", "sunday", "monday"}},
{"zero-steps", "monday", 0, []string{}},
{"more-than-a-week", "sunday", 9, []string{"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"}},
{"unknown", "funday", 3, []string{}},
{"wrong-case", "Friday", 2, []string{}},
{"number", "3", 2, []string{}},
{"empty-name", "", 1, []string{}},
}
func TestCycle(t *testing.T) {
for _, c := range cases {
if got := Cycle(c.start, c.steps); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestString(t *testing.T) {
if got := fmt.Sprint(Friday, int(Friday)); got != "friday 4" {
t.Errorf("got %q", got)
}
if got := Day(9).String(); got != "Day(?)" {
t.Errorf("got %q", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
/// The days of the week. Each variant has no data, so `as usize` gives its
/// position.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
impl Day {
/// Rust cannot loop over the variants of an enum, so a constant array
/// lists them.
pub const ALL: [Day; 7] = [
Day::Monday,
Day::Tuesday,
Day::Wednesday,
Day::Thursday,
Day::Friday,
Day::Saturday,
Day::Sunday,
];
pub fn name(self) -> &'static str {
match self {
Day::Monday => "monday",
Day::Tuesday => "tuesday",
Day::Wednesday => "wednesday",
Day::Thursday => "thursday",
Day::Friday => "friday",
Day::Saturday => "saturday",
Day::Sunday => "sunday",
}
}
pub fn parse(s: &str) -> Option<Day> {
Day::ALL.into_iter().find(|d| d.name() == s)
}
}
/// Returns steps day names from start on, with monday after sunday.
pub fn cycle(start: &str, steps: usize) -> Vec<&'static str> {
let Some(day) = Day::parse(start) else {
return Vec::new();
};
let i = day as usize;
(0..steps).map(|k| Day::ALL[(i + k) % Day::ALL.len()].name()).collect()
}
tests/cycle_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-an-enumeration/.
use algo_define_an_enumeration::{Day, cycle};
#[test]
fn cases() {
let cases: Vec<(&str, &str, usize, Vec<&str>)> = vec![
("weekdays", "monday", 3, vec!["monday", "tuesday", "wednesday"]),
("wrap", "friday", 4, vec!["friday", "saturday", "sunday", "monday"]),
("zero-steps", "monday", 0, vec![]),
("more-than-a-week", "sunday", 9, vec!["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"]),
("unknown", "funday", 3, vec![]),
("wrong-case", "Friday", 2, vec![]),
("number", "3", 2, vec![]),
("empty-name", "", 1, vec![]),
];
for (name, start, steps, want) in cases {
assert_eq!(cycle(start, steps), want, "case {name}");
}
}
#[test]
fn to_and_from_int() {
assert_eq!(Day::Friday as usize, 4);
assert_eq!(Day::ALL[4], Day::Friday);
assert_eq!(Day::parse("friday"), Some(Day::Friday));
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-an-enumeration/.
# Bash has no enum. An indexed array lists the names in order, and the index
# of a name is its integer value.
DAYS=(monday tuesday wednesday thursday friday saturday sunday)
# cycle START STEPS
# Prints STEPS day names, one on each line, from START on, with monday after
# sunday. Prints nothing if START is not a name.
cycle() {
local start=$1 steps=$2 i k
for i in "${!DAYS[@]}"; do
if [[ ${DAYS[i]} == "$start" ]]; then
for ((k = 0; k < steps; k++)); do
printf '%s\n' "${DAYS[(i + k) % ${#DAYS[@]}]}"
done
return 0
fi
done
}
test_cycle.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-an-enumeration/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/cycle.sh"
}
check() { # check WANT START STEPS
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=$(cycle "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "weekdays" { check "monday\ntuesday\nwednesday\n" monday 3; }
@test "wrap" { check "friday\nsaturday\nsunday\nmonday\n" friday 4; }
@test "zero-steps" { check "" monday 0; }
@test "more-than-a-week" { check "sunday\nmonday\ntuesday\nwednesday\nthursday\nfriday\nsaturday\nsunday\nmonday\n" sunday 9; }
@test "unknown" { check "" funday 3; }
@test "wrong-case" { check "" Friday 2; }
@test "number" { check "" 3 2; }
@test "empty-name" { check "" "" 1; }
References
- The Python Standard Library, enum, the introduction; EnumType; StrEnum
- Java SE 27 API, Class Enum, ordinal(); valueOf(Class, String)
- C# reference, Enumeration types, the introduction; Conversions
- The Go Programming Language Specification, Iota
- The Rust Reference, Enumerations, Casting
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.7.2.2 Enumeration specifiers
- cppreference.com, Enumeration declaration, Scoped enumerations
- MDN Web Docs, Object.freeze(), Description
- TypeScript Handbook, Enums, Objects vs Enums
- Bash Reference Manual, 6.7 Arrays
- .NET API reference, Enum.TryParse method, Remarks
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 Z8JRWK Edit this page History Report an error Markdown