title: In Haskell how to pass a constructor as a parameter and match over it
body: <p>I have this code</p>
  
  <pre><code>data Container = Box Int | Bag Int
  
  
  inBox :: [Container] -&gt; Int
  inBox [] = 0
  inBox (x:ls) | (Box i) &lt;- x = i + inBox ls
               | otherwise = inBox ls
  
  
  inBag :: [Container] -&gt; Int
  inBag [] = 0
  inBag (x:ls) | (Bag i) &lt;- x = i + inBag ls
               | otherwise = inBag ls
  </code></pre>
  
  <p>Clearly <code>InBox</code> and <code>InBag</code> have the same structure. I would like to make a function that encompass both of them. What I don't know how to get is to pass the constructor (either <code>Box</code> or <code>Bag</code>) as a parameter. </p>
  
  <p>Ideally, the general function woul look something like this:</p>
  
  <pre><code>inSome :: Constructor -&gt; [Container] -&gt; Int
  inSome con [] = 0
  inSome con (x:ls) | (con i) &lt;- x = i + inSome con ls
                    | otherwise = inSome con ls
  </code></pre>
  
  <p>Obviously that doesn't work because constructor is not a defined type here. How can I do it?</p>
  
  <p>One idea is to pass it as a function like so:</p>
  
  <pre><code>inSome :: (Int -&gt; Container) -&gt; [Container] -&gt; Int
  inSome _ [] = 0
  inSome con (x:ls) | (con i) &lt;- x = i + inSome ls
                    | otherwise = inSome ls
  </code></pre>
  
  <p>But then I get the error:</p>
  
  <blockquote>
    <p>Parse error in pattern: con</p>
  </blockquote>
  
  <p>Because it cannot match on functions like that.</p>
  
  <p>The reason I want to do this is because I have a complicated data type that includes binary operations (e.g. +, #, ::, etc...) I have several functions that are almost identical for these constructors. I would hate to write all of them and modify them all together. There must me a way to do it in a function. Maybe someone can suggest another approach in the comments?</p>