resistor-color

This commit is contained in:
Alexander Heldt
2025-11-08 11:16:09 +01:00
parent 0df72539ef
commit 1c8dcb28be
9 changed files with 285 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
pub type Color {
Black
Brown
Red
Orange
Yellow
Green
Blue
Violet
Grey
White
}
pub fn code(color: Color) -> Int {
case find_index(colors(), fn(c) { c == color }) {
Error(_) -> -1
Ok(code) -> code
}
}
pub fn colors() -> List(Color) {
[Black, Brown, Red, Orange, Yellow, Green, Blue, Violet, Grey, White]
}
fn find_index(list: List(a), predicate: fn(a) -> Bool) -> Result(Int, Nil) {
find_index_loop(list, predicate, 0)
}
fn find_index_loop(
list: List(a),
predicate: fn(a) -> Bool,
index: Int,
) -> Result(Int, Nil) {
case list {
[] -> Error(Nil)
[head, ..tail] ->
case predicate(head) {
True -> Ok(index)
False -> find_index_loop(tail, predicate, index + 1)
}
}
}