Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think this question is about performance. While <em>semantically</em> pattern matching is tested top-to-bottom, most Haskell compilers will optimize matching on an ADT's constructors to the equivalent of a C <code>switch</code> statement. </p> <p>You can think of the data representation for an ADT has a "tag" which says which constructor it was made with, together with a pointer for each argument. So for example, <code>Nothing</code> might be represented as <code>0 (null)</code> and <code>Just 42</code> represented as <code>1 (pointer to 42)</code>.</p> <p>Then in a function like this:</p> <pre><code>squash :: Maybe (Maybe Int) -&gt; Int squash (Just Nothing) = 0 squash Nothing = 0 squash (Just (Just x)) = x </code></pre> <p>The compiler would set up a decision tree:</p> <pre><code>squash x = check tag of x: 0 -&gt; 0 1 y -&gt; check tag of y: 0 -&gt; 0 1 z -&gt; z </code></pre> <p>Where each tag is computed by a jump table or something, so it is no more expensive to check against <code>0</code> as <code>1</code>. Note that this same decision tree would be made no matter what the original order of the patterns in our definition.</p> <p>However, when using guards instead of matching on a constructor, the patterns are most likely checked from top to bottom (the compiler would have to be <em>very</em> smart to optimize that). So if we wrote <code>fromJust</code> in this arcane way:</p> <pre><code>fromJust x | isNothing x = error "fromJust: Nothing" | isJust x = case x of { Just y -&gt; y } </code></pre> <p>Then this would probably check for each constructor in turn, and we could optimize by switching the order of the cases. Fortunately, writing in a way that this matters is cumbersome :-).</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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