title: Generic function result in Haskell based on some predicates
body: <p>Is it possible to write a function in haskell, which returns a generic type when:</p>
  
  <ul>
  <li>in the body of this function we output as a result 2 separate types <code>A</code> and <code>B</code> (based on some computations)</li>
  <li>types <code>A</code> and <code>B</code> have a common <code>type class</code> <code>C</code></li>
  </ul>
  
  <p>Lets see the sample code. The type checker SHOULD be able to check, that this code is correct - function <code>test</code> outputs instance of type <code>A</code> or <code>B</code>, so we can perform <code>f</code> on the result.</p>
  
  <pre><code>data A = A 
  data B = B
  
  class C a where
      f :: a -&gt; Int
  
  instance C A where
      f x = 2
  
  instance C B where
      f x = 3
  
  -- This function fails to compile:
  -- I want something like:
  -- test :: C a =&gt; Int -&gt; a
  test x = if x &lt; 1  
          then A
          else B
  
  main = do
      print $ f $ test 0
      print $ f $ test 1
  </code></pre>
  
  <p><strong>I know this could look like anti-pattern or something like that, but I want to know the answer because I love to test Haskell features, especially when it comes to the type system.</strong></p>