title: How to return type of certain typeclass in a function
body: <p>I would like to remove the repetitive code in the following code, by providing a function that returns a value of instance of certain typeclass(ClassA in this example):</p>
  
  <pre class="lang-hs prettyprint-override"><code>class ClassA a where
    f :: a -&gt; Int
  data A1 = A1 Int Int
  instance ClassA A1 where
    f (A1 v1 v2) = v1 + v2
  data A2 = A2 Int Int
  instance ClassA A2 where
    f (A2 v1 v2) = v1 * v2
  
  g1 :: ClassA a =&gt; a -&gt; Int
  g1 iA = f iA + 1
  g2 :: ClassA a =&gt; a -&gt; Int
  g2 iA = f iA + 2
  
  class ClassB b where
    newB :: Int -&gt; b
    h1 :: b -&gt; Int
    h2 :: b -&gt; Int
  
  data B1 = B1 A1
  fromB1toA1 :: B1 -&gt; A1
  fromB1toA1 (B1 a) = a
  instance ClassB B1 where
    newB v = B1 (A1 v v)
    h1 b = let a = fromB1toA1 b in g1 a -- repeative code!!
    h2 b = let a = fromB1toA1 b in g2 a -- repeative code!!
  
  data B2 = B2 A2
  fromB2toA2 :: B2 -&gt; A2
  fromB2toA2 (B2 a) = a
  instance ClassB B2 where
    newB v = B2 (A2 v v)
    h1 b = let a = fromB2toA2 b in g2 a -- repeative code!!
    h2 b = let a = fromB2toA2 b in g2 a -- repeative code!!
  
  main = do
    let a1 = A1 2 4
    let a2 = A2 2 4
    print (f a1, g1 a1, g2 a1)
    print (f a2, g1 a2, g2 a1)
  
    let b1 = B1 (A1 5 5)
    let b2 = B2 (A2 6 6)
    print (h1 b1, h2 b1)
    print (h1 b2, h2 b2)
  
    print "bye"
  </code></pre>
  
  <p>I was trying to do things like this, but it didn't compile for me:</p>
  
  <pre class="lang-hs prettyprint-override"><code>class ClassB b where
    newB :: Int -&gt; b
    toClassA :: (ClassA a) =&gt; b -&gt; a
    h1 :: b -&gt; Int
    h1 b = let a = toClassA b in g1 a -- doesn't compile
    h2 :: b -&gt; Int
    h2 b = let a = toClassA b in g2 a -- doesn't cimpile
  
  data B1 = B1 A1
  instance ClassB B1 where
    newB v = B1 (A1 v v)
    toClassA (B1 a) = a -- doesn't compile
  
  data B2 = B2 A2
  instance ClassB B2 where
    newB v = B2 (A2 v v)
    toClassA (B2 a) = a  -- doesn't compile
  </code></pre>