I have this data type
data Struct val = Empty | Exec1 val
| Exec2 val
And two dummy functions
apply :: Struct -> String
apply (Empty) = "matched Empty"
apply (exec struct) = "matched Exec1 or Exec2"
apply' :: Struct val -> String
apply' (Empty) = "matched Empty"
apply' (Exec1 _) = "matched Exec1"
apply' (Exec2 _) = "matched Exec2"
Second one is working fine, but the first one is causing error: “Parse error in pattern: exec”. Can you plase explain why can’t I match on constructor this way:
apply (exec struct) = … ?
It’s causing a lot of boilerplate code when I have multiple constructors in my datatype and must pattern match them all separately.
Why? Because you can only match constructors, and
execis kind of a new variable. One reason for this is for example the following:How should anyone know which of
Exec1andExec2you are matching? You couldn’t apply functions here, since the actual type ofstructcouldn’t be determined.If you want to reduce the pattern matching, there are a number of ways, from using
case, over differentdataimplementation (like @Karolis suggested) and helper functions to higher level constructs with more complex types. But that’s an endless topic.