I'm pattern matching on the data constructor of a record, and I have the following chunk of code:
colorFor shape =
case material shape of
ColorMaterial -> material shape
-- etc.
The problem is this: material is a nontrivial method, and I'd like to not recompute it in the case statement. I know I could do something like:
colorFor shape =
let m = material shape
in case m of
ColorMaterial -> m
or
colorFor shape =
case material shape of
ColorMaterial r g b -> ColorMaterial r g b
But I couldn't help but think there must be some way to retrieve the matched value in a pattern match. This also comes up for function definitions, where I'd like to match on the data constructor for some argument without completely unpacking it.
FYI: I'm new to Haskell, and if there are better ways of doing what I'm doing I'm very open to suggestion. Any help greatly appreciated!
You are looking for "as patterns":
data SomeDataType = ColorMaterial Int Int Int
| BlandMaterial
colorFor shape =
case material shape of
res@(ColorMaterial _ _ _) -> res
-- etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With