#Resistor Color Cases

1 messages · Page 1 of 1 (latest)

prisma parcel
#

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?
red tundra
#

The "color" pattern matches any value and binds it to the name "color", it doesn't compare it to the existing color variable. You can add a guard like if c == color

.. matches the rest of the list, so you can't have anything after it since there's nothing left to match. You can only match the start of the list and then the rest.

The correct spelling is colour.

prisma parcel
#

oh I understand now about the value binding, in my case it would be similar to multiple let statements that redefine the same variable right?

I see now that the 'List Patterns' section of the book uses the wording 'can be used to match the rest of the list'. I guess I assumed that using it at the beginning to match the 'rest' of the list at the beginning would be logically consistent with that phrasing.

prisma parcel
#

okay I realize that I was wayyyy overcomplicating it and assumed I had to use the function that returned the colors in a list inside the function that returned the code for the corresponding color

#

also that the most simple solution is just a modified version of the code in the 'Custom Types' example in the book

opaque turret