Skip to content

Resistor Color

Look up the digit a resistor band’s color stands for, and list the colors in value order.

Adapted from Exercism’s problem specification (MIT). Listed under Encoding & Ciphers.

// FILE: resistor_color.nomi
//# The values of a resistor's color bands.

/// A band color, in value order: black is 0 and white is 9.
pub enum Color
    Black
    Brown
    Red
    Orange
    Yellow
    Green
    Blue
    Violet
    Grey
    White
end

derive Variants for Color

/// The digit `color` stands for on a band.
pub fn color_code(color: Color) -> Int
    case color
        .Black  -> 0
        .Brown  -> 1
        .Red    -> 2
        .Orange -> 3
        .Yellow -> 4
        .Green  -> 5
        .Blue   -> 6
        .Violet -> 7
        .Grey   -> 8
        .White  -> 9
    end
end

/// Every band color, in value order.
pub fn colors() -> List<Color>
    Color.variants()
end

// FILE: resistor_color_test.nomi
import
    resistor_color
    resistor_color.Color
end

test "Color codes"
    [
        ("Black",  Color.Black, 0),
        ("White",  .White,      9),
        ("Orange", .Orange,     3),
    ]
    |> subtests (description, color, expected), description
        assert resistor_color.color_code(color) == expected
    end
end

test "Colors"
    assert resistor_color.colors() == [
        .Black,
        .Brown,
        .Red,
        .Orange,
        .Yellow,
        .Green,
        .Blue,
        .Violet,
        .Grey,
        .White,
    ]
end
  • The colors are an enum, Color, rather than the canonical strings; the tests write Color.Black where the data says "black".
  • color_code spells each value out in a case rather than taking the color’s position in Color.variants(). The position would be a search, Iter.find_index(...)!, whose trap the reader has to see cannot happen, and the table is what the problem states.
  • colors is Color.variants() from derive Variants, which lists the variants in declaration order, the value order.
  • The expected list in the Colors test qualifies only its first element ([Color.Black, .Brown, ...]); the later bare variants take its enum.