title: Extracting an Id with GHC.Generics
body: <p>How to extract an identifier (in this case an integer) from a structure using <code>GHC.Generics</code>?</p>
  
  <p>I have an <code>Id</code> type:</p>
  
  <pre><code>newtype Id = Id { _id :: Int }
  </code></pre>
  
  <p>and a lot of types that use that type:</p>
  
  <pre><code>data VarId = VarId Name Id SortId
  data FuncId = FuncId Name Id [SortId] SortId
  data SortId = Name Id
  -- ... and 20 more of these things
  </code></pre>
  
  <p>On top of that there are other types that wrap the types above, for instance, identifiers:</p>
  
  <pre><code>data Identifier = IdVar VarId
                  | IdFunc FuncId
                  | IdSort SortId
                  -- ... and 20 more of these things
  </code></pre>
  
  <p>Now I need to extract the <code>_id</code> field from any of these types containing an <code>Id</code> value. Currently we have tons of boilerplate for this, and I want to scrap it away using generics.</p>
  
  <p>At first I thought about defining a class:</p>
  
  <pre><code>class Identifiable e where
      getId :: e -&gt; Id
  
      default getId :: (Generic e, GIdentifiable (Rep e)) =&gt; e -&gt; Id
      getId = gGetId . from
  
  class GIdentifiable f where
      gGetId :: f e -&gt; Id
  </code></pre>
  
  <p>in such a way that you'd have an <code>Identifiable</code> instance <strong>only</strong> if there is  one such <code>Id</code> type inside (in case that there are multiple of those like in <code>FuncId</code> above we return the first <code>Id</code> found when traversing the structure from top to bottom). Now the problem comes when I try to define the <code>GIdentifiable</code> instances for the product and sum. I would like to express something like:</p>
  
  <pre><code>instance (GIdentifiable a) =&gt; GIdentifiable (a :*: b) where
      gGetId (a :*: _) = gGetId a
  
  instance {-# OVERLAPS #-} (GIdentifiable b) =&gt; GIdentifiable (a :*: b) where
  gGetId (_ :*: b) = gGetId b
  </code></pre>
  
  <p>Which won't work because I'm defining duplicate instances. </p>
  
  <p>I could redefine <code>Identifiable</code> so that <code>getId :: e -&gt; Maybe Id</code> but this will remove some of the type safety, and introduce unnecessary checks when <strong>I know</strong> that a type contains at least one <code>Id</code>.</p>
  
  <p>Is there a way to express this sort of case analysis when working with the type system?</p>