title: Haskell reuse patterns
body: <p>In the code below, the same pattern match <strong>(Node n left right)</strong> is used by three different functions. If I want to add a pattern, e.g. <strong>(Node n (Leaf) (Leaf))</strong> or change my datatype, I have to change all the functions. Is there a way to reuse these patterns, so I only have to define them once?</p>
  
  <pre><code>data Tree = Node Int Tree Tree
            | Leaf 
  
  add :: Tree -&gt; Int -&gt; Tree
  add (Node n left right) x = Node (n+x) (add left x) (add right x) 
  add (Leaf) x = Leaf
  
  subtract :: Tree -&gt; Int -&gt; Tree
  subtract (Node n left right) x = Node (n-x) (subtract left x) (subtract right x) 
  subtract (Leaf) x = Leaf
  
  swap :: Tree -&gt; Tree
  swap (Node n left right) = Node n right left
  swap (Leaf) = Leaf
  </code></pre>
  
  <p>I tried </p>
  
  <pre><code>matchNode = (PNode n left right)
  add matchNode x = Node (n+x) (add left x) (add right x) 
  </code></pre>
  
  <p>but it won't allow me to use the pattern _, and I can't extract <strong>n</strong>, <strong>left</strong>, and <strong>right</strong> from it.</p>