Hello! I'm trying the resistor color exercise on Exercism and I'm not exactly sure why my cases aren't working correctly. I come from a typescript background so the pattern matching doesn't come naturally yet but I really want to get good at it and fully understand what I'm doing when I use pattern matching.
What I assumed my code was doing was pattern matching on the list returned by the colors function and then returning an index based on where the requested color existed in the list. when I run the tests the only color code test that succeeds is the one for black which is the very first match statement. why is my pattern matching not correctly covering the other tests?
pub fn code(color: Color) -> Int {
case colors() {
[color, ..] -> 0
[_, color, ..] -> 1
[_, _, color, ..] -> 2
[_, _, _, color, ..] -> 3
[_, _, _, _, color, ..] -> 4
[_, _, _, _, _, color, ..] -> 5
[_, _, _, _, _, _, color, ..] -> 6
[_, _, _, _, _, _, _, color, ..] -> 7
[_, _, _, _, _, _, _, _, color, _] -> 8
[.., color] -> 9
_ -> 0
}
}
pub fn colors() -> List(Color) {
[Black, Brown, Red, Orange, Yellow, Green, Blue, Violet, Grey, White]
}```
sidenote: I forgot that I had commented out the final color code case that returns the index 9 while running the tests because when I have that included I get this error:
error: Syntax error
┌─ src/resistor_color.gleam:27:10
│
27 │ [.., color] -> 9
│ ^^^^^ I was not expecting this
Expected one of:
"]"
a pattern
why does putting a comma after this spread break the code?