Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use matched value in case construct in Haskell

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!

like image 606
Haldean Brown Avatar asked Dec 07 '25 08:12

Haldean Brown


1 Answers

You are looking for "as patterns":

data SomeDataType = ColorMaterial Int Int Int
                  | BlandMaterial

colorFor shape = 
  case material shape of
    res@(ColorMaterial _ _ _) -> res
    -- etc.
like image 135
Thomas M. DuBuisson Avatar answered Dec 08 '25 23:12

Thomas M. DuBuisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!