Skip to content

Series

List every run of adjacent digits of a given length in a string of digits, in order.

Adapted from Exercism’s problem specification (MIT). Listed under Strings & Text.

// FILE: series.nomi
//# The runs of adjacent digits of one length in a string of digits.

/// Why a series has no slices of the length asked for.
pub enum Error
    EmptySeries
    ZeroLength
    NegativeLength
    LengthTooLarge
end

/// Every run of `length` adjacent characters in `series`, in the order they
/// start. Runs overlap, and equal runs are all kept.
pub fn slices(series: String, length: Int) -> Result<List<String>, Error>
    size = String.length(series)

    case
        size == 0 -> Err(.EmptySeries)
        length < 0 -> Err(.NegativeLength)
        length == 0 -> Err(.ZeroLength)
        length > size -> Err(.LengthTooLarge)
        _ -> series |> Iter.windows(length) |> Iter.map(String.join) |> Iter.to_list() |> Ok()
    end
end

// FILE: series_test.nomi
import series.{self, Error}

test "slices"
    [
        ("slices of one from one",        "1",      1, ["1"]),
        ("slices of one from two",        "12",     1, ["1", "2"]),
        ("slices of two",                 "35",     2, ["35"]),
        ("slices of two overlap",         "9142",   2, ["91", "14", "42"]),
        ("slices can include duplicates", "777777", 3, ["777", "777", "777", "777"]),
        (
            "slices of a long series",
            "918493904243",
            5,
            ["91849", "18493", "84939", "49390", "93904", "39042", "90424", "04243"],
        ),
    ]
    |> subtests (description, digits, length, expected), description
        assert series.slices(digits, length) == Ok(expected)
    end
end

test "errors"
    [
        ("slice length is too large",       "12345", 6,  Error.LengthTooLarge),
        ("slice length is way too large",   "12345", 42, .LengthTooLarge),
        ("slice length cannot be zero",     "12345", 0,  .ZeroLength),
        ("slice length cannot be negative", "123",   -1, .NegativeLength),
        ("empty series is invalid",         "",      1,  .EmptySeries),
    ]
    |> subtests (description, digits, length, expected), description
        assert series.slices(digits, length) == Err(expected)
    end
end
  • Errors are an Error enum with one variant per canonical message. The checks run in the order the canonical cases need: an empty series is EmptySeries even when the length is also too large.

  • The validation is a case with no subject, since each condition compares different values.

  • The runs are Iter.windows(series, length) over the string’s graphemes, each joined back into a string. The function works on graphemes, not only digits.

  • The test file splits the canonical cases into two subtests tables, one for Ok results and one for errors, so each table makes one claim. The test binds the input as digits, since series is the module’s name there.