Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to express pattern matching for independent combinations of data values?
    primarykey
    data
    text
    <pre><code>data Foo = Bar1 | Bar2 Foo Foo | Bar3 Foo | Bar4 Foo Foo Foo </code></pre> <p>Now, assume someone built a <code>Foo</code> tree and I want to check if the arguments of a Foo value are valid. The rules on the constructor arguments are:</p> <ul> <li><code>Bar2 Bar1 Foo</code></li> <li><code>Bar3 (Bar2|Bar3|Bar4)</code></li> <li><code>Bar4 Bar1 Bar1 (Bar1|Bar4)</code></li> </ul> <p>I know the constructor of the value and only want to check the immediate arguments, nothing recursive. Like this:</p> <pre><code>bar2 Bar1 Bar1 = True bar2 Bar1 (Bar2 {}) = True bar2 Bar1 (Bar3 _) = True bar2 Bar1 (Bar4 {}) = True bar2 _ _ = False </code></pre> <p>And e.g. similarly for Bar4:</p> <pre><code>bar4 Bar1 Bar1 Bar1 = True bar4 Bar1 Bar1 (Bar4 {}) = True bar4 _ _ _ = False </code></pre> <p>How can I express these conditions most concisely? Listing all combinations is in some cases a bit too much. And to my knowledge an "OR"-syntax for pattern matching doesn't exist.</p> <p><em>UPDATE</em></p> <p>I adapted Daniel's solution and have come to this:</p> <pre><code>data Foo = Bar1 | Bar2 Foo Foo | Bar3 Foo | Bar4 Foo Foo Foo deriving (Data, Typeable) bar2 a b = a `isOf` [Bar1] &amp;&amp; b `isOf` [Bar1,Bar2{},Bar3{},Bar4{}] bar4 a b c = [a,b] `areOf` [Bar1] &amp;&amp; c `isOf` [Bar1,Bar4{}] isOf l r = toConstr l `elem` map toConstr r areOf l r = all (`isOf` r) l </code></pre> <p>What I like about this is that I don't have to change my data type, except adding the deriving clause, and that it's readable. The disadvantage of course is that these are dynamic checks. In my case this is fine though as it's just for assert-like checks to discover programming errors.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload