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,
]
endok Color codes (3 cases)
ok Colors
test result: ok. 4 passed, 0 failed
How it’s written
Section titled “How it’s written”- The colors are an enum,
Color, rather than the canonical strings; the tests writeColor.Blackwhere the data says"black". color_codespells each value out in acaserather than taking the color’s position inColor.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.colorsisColor.variants()fromderive Variants, which lists the variants in declaration order, the value order.- The expected list in the
Colorstest qualifies only its first element ([Color.Black, .Brown, ...]); the later bare variants take its enum.