Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell alternative to long list of pattern matches?

I have a function that outputs a booleanlike property given a datatype. This function calculates the property by pattern matching on the first constructor of the datatype, so something like

data C = C1 | C2 | .. | Cn 

f :: C -> Bool 
f (C1 _ _ ... _) = True
f (C2 _ _ ... _) = True
f (C3 _ _ ... _) = False
.
.
.
f (Cn _ _ ..._) = False

Is there a more compact way to perform pattern-matching, or is there another (also more compact) way to go about my property checking? I prefer not to add the property to the data type definition since it can be calculated with relative ease.

like image 911
Haxelaar Avatar asked Feb 20 '14 11:02

Haxelaar


1 Answers

You can avoid the wildcard patterns using record syntax. Also, use a case expression to avoid having to repeat the function name, e.g.

f :: C -> Bool
f x = case x of
  C1 {} -> True
  C2 {} -> False
  ...
  Cn {} -> False

That's about as compact as it's going to get without changing your data type.

like image 121
hammar Avatar answered Oct 23 '22 19:10

hammar