title: How to write a generic function for any data constructor?
body: <p>Suppose I have these definitions of a data in Haskell.</p>
  
  <pre><code>data Point a = Point a a
  data Piece a = One a | Two a
  </code></pre>
  
  <p>and I want to have one function like</p>
  
  <pre><code>place :: Num a =&gt; Piece (Point a) -&gt; Point a
  place (Piece x) = x
  </code></pre>
  
  <p>how do I do this since haskell doesn't allow functions of that particular form.</p>
  
  <p><strong>Solution</strong></p>
  
  <p>The problem was my data definition (many years of empirical programming is interfering here...). I wanted my Piece data to effectively be 2 different things, a Piece and also a kind of piece, I tried to achieve this with inheritance which was just a bad approach. Separating data in the following way solved the problem.</p>
  
  <pre><code>data PieceKind = One | Two | ... | n
  data Piece a b = Piece a PieceKind
  </code></pre>
  
  <p>This way my Piece effectively has two attributes "a" (in my case this is a position of a piece) and also PieceKind, this way I was able to write the place function without having to repeat it for every kind of piece in the following way:</p>
  
  <pre><code>place :: Num a =&gt; Piece (Point a) PieceKind -&gt; Point a
  place (Piece x _) = x
  </code></pre>
  
  <p>In addition I was also able to write functions for a particular kind of a Piece:</p>
  
  <pre><code>place :: Num a =&gt; Piece (Point a) PieceKind -&gt; Point a
  place (Piece _ One) = ...
  </code></pre>
  
  <p>and this is what I really wanted.</p>