Shadowing & pattern matching

Let’s say I want to define a Color (using the elm.color package) as

orangeColor : Color
orangeColor =
     rgb 255 180 0

… elsewhere, I need to turn all my Colors into strings (as elm/svg demands)

I therefore use a case expression:

colorString : Color -> String
colorString c =

case c of
    orangeColor -> "orange"
    ..
    ..
    _ -> "gray"

Up comes the 0.19 error message

SHADOWING - The name `orangeColor` is first defined here:

275| orangeColor =
     #^^^^^^^^^^^#
But then it is defined AGAIN over here:

130|       orangeColor -> "orange"
           #^^^^^^^^^^^#
Think of a more helpful name for one of them and you should be all set!

Er, excuse me, but if I think of “a more helpful name for one of them”, then it won’t match… Not quite what I’d call being “all set”.

The recommended documentation on shadowing is here, but I don’t see how it applies to pattern matching.

Unfortunately, the rules of pattern matching specify that putting a variable name as the pattern means you’re asking to have that variable created (i.e. match anything).

I’m not sure if there’s a way to get Elm to recognise that you want to compare the two variables (other than changing to an if-expression).

I know I’m not actually answering your question, but instead I’m trying to guess what you actually wanted to do and bring you on the right track.

1.
Which package do you mean by elm.color?
Do you perhaps mean this one?

2.

elsewhere, I need to turn all my Colors into strings (as elm/svg demands)
I therefore use a case expression

Why? It seems like you are trying to use the colors as a css color string.
If so and if you use the color package mentioned above, you could directly use toCssString.
And if you aren’t using this one, I bet it will allow something like this:

colorString c =
    let
        {r, g, b} = Color.toRecord c
    in
    "rgba(" ++ String.fromFloat r ++ "," ++ String.fromFloat g ++ "," ++ String.fromFloat b ++")"

As for your question, I think @nmsmith already answered it nicely.
You can only match on literals, not based on the content of an existing variable.
Pattern matching is most useful when it involves custom types. If you haven’t read the full guide yet, I especially recommend these two pages: custom types and pattern matching

Yes, that was the Color package I was using.

I abandoned that package and refactored everything to make the colors into an ADT, so I can easily pattern match them.

I’ve been away from Elm for a while, so was surprised that I couldn’t pattern match on a variable. I shouldn’t have been surprised, since I’ve been working in F#, where the same restriction applies, except that F# has a special construct called Active Patterns to get round this.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.