title: Returning a value of any type that implements a specific typeclass
body: <p>Suppose I have</p>
  
  <pre><code>class A a where
      a :: a
  
  data A' = A' Int
  
  instance A A' where
      a = A' 0
  
  selectA :: A a =&gt; Int -&gt; Maybe a
  selectA _ = Just (A' 0)
  </code></pre>
  
  <p>As you can see, <code>selectA</code> is supposed to select some value whose type implements <code>A</code>. Note: The type of <code>a</code> doesn't have to be <code>a</code>, and it could be something else, e.g. <code>a -&gt; Char</code>. Anyway, considering that <code>A'</code> is a member of the class <code>A</code>, I would expect this implementation of <code>selectA</code> to work. However, compiling this gives the following error:</p>
  
  <pre class="lang-none prettyprint-override"><code>• Couldn't match type ‘a’ with ‘A'’
    ‘a’ is a rigid type variable bound by
      the type signature for:
        selectA :: forall a. A a =&gt; Int -&gt; Maybe a
      at --
    Expected type: Maybe a
      Actual type: Maybe A'
  • In the expression: Just (A' 0)
    In an equation for ‘selectA’: selectA _ = Just (A' 0)
  • Relevant bindings include
      selectA :: Int -&gt; Maybe a (bound at --)
  </code></pre>
  
  <p>My undestanding is that this problem arises from the caller of <code>selectA</code> being able to decide the exact type of <code>a</code>. I'm only interested in getting <em>something</em> that implements <code>A</code>. This would solve the problem if it was possible:</p>
  
  <pre><code>selectA :: Int -&gt; Maybe (A a =&gt; a)
  </code></pre>
  
  <p>Unfortunately this is not possible. How do I get similar functionality?</p>