Skip to content

Resistor Color Duo

Read a resistor’s first two color bands as a two-digit number, ignoring any band after them.

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

// FILE: resistor_color_duo.nomi
//# The two-digit value a resistor's first two color bands give.

/// 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

/// The value the first two bands read as digits give, ignoring any band
/// after them, or `None` when there are fewer than two bands.
pub fn value(bands: List<Color>) -> Maybe<Int>
    case bands
        [first, second, ..] -> Some(digit(first) * 10 + digit(second))
        _                   -> None
    end
end

fn digit(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

// FILE: resistor_color_duo_test.nomi
import
    resistor_color_duo
    resistor_color_duo.Color
end

test "value"
    [
        ("Brown and black",            [Color.Brown, .Black],     10),
        ("Blue and grey",              [.Blue, .Grey],            68),
        ("Yellow and violet",          [.Yellow, .Violet],        47),
        ("White and red",              [.White, .Red],            92),
        ("Orange and orange",          [.Orange, .Orange],        33),
        ("Ignore additional colors",   [.Green, .Brown, .Orange], 51),
        ("Black and brown, one-digit", [.Black, .Brown],          1),
    ]
    |> subtests (description, bands, expected), description
        assert resistor_color_duo.value(bands) == Some(expected)
    end
end

// Not a canonical case: the exercise always gives at least two bands.
test "fewer than two bands have no value"
    assert resistor_color_duo.value([.Brown]) == None
end
  • value takes the bands as a List<Color>, since one canonical case passes three, and matches [first, second, ..].
  • Fewer than two bands answer None, so value returns Maybe<Int>. The canonical data never gives fewer; the test file adds one such case, marked as not canonical. A band list is data the caller may have read from anywhere, so a missing band is an answer rather than a trap (style §29).
  • The Color enum and its digit table are repeated from resistor-color: each exercise stands alone.
  • The table qualifies only the first row’s first color ([Color.Brown, .Black]); every later bare variant, in its own row’s list, takes that enum.