title: Record selectors in Haskell's Type Classes
body: <p>I want to implement a <code>Type Class</code> with few default methods, but I'm getting an error, that I cannot use <code>record selectors</code> inside <code>type classes</code> definitions. </p>
  
  <p>The following code basically creates <code>type class</code> which defines <code>add</code> function, which should add an element to the <code>repr</code> record of some <code>data type</code>. Here is the code:</p>
  
  <pre><code>import qualified Data.Graph.Inductive     as DG
  
  class Graph gr a b where
      empty :: DG.Gr a b
      empty = DG.empty
  
      repr :: gr -&gt; DG.Gr a b
  
      -- following function declaration does NOT work:
      add :: a -&gt; gr -&gt; gr
      add el g = g{repr = DG.insNode el $ repr g}
  </code></pre>
  
  <p>The compiler throws error:</p>
  
  <pre><code>repr is not a record selector
  In the expression: g {repr = DG.insNode el $ repr g}
  In an equation for add:
      add el g = g {repr = DG.insNode el $ repr g}
  </code></pre>
  
  <p>Is it possible to declare such methods in Haskell?</p>
  
  <p><strong>Clarification</strong></p>
  
  <p>I need such design because I've got some <code>data types</code>, which behave in simmilar way. Lets say, we got <code>A</code>, <code>B</code> and <code>C</code> <code>data types</code>. Each of them should have a record <code>repr :: DG.Gr a b</code>, where <code>a</code> and <code>b</code> are distinct for each of <code>A</code>, <code>B</code> and <code>C</code>.</p>
  
  <p><code>A</code>, <code>B</code> and <code>C</code> share the same functions, like <code>add</code> or <code>delete</code> (which basically add or delete elements to record <code>repr</code>). If these data types share a lot of functions it make sense to implement the functions in <code>type class</code> and make instances of this <code>type class</code> - these functions will be implemented for each of our <code>data type</code> automatically.</p>
  
  <p>Additional I would love some of these <code>data types</code> (lets say I want <code>B</code>) to behave slighty different when calling <code>add</code> function on it. It is easy to implement this behaviour when making <code>instance</code> of the <code>type class</code> for <code>B</code>.</p>