title: Can multiple dispatch be achieved in Haskell with pattern matching on type classes?
body: <p>This is a question about <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="noreferrer">multiple dispatch</a> in Haskell.</p>
  
  <p>Below I use the term "compliant to [type class]" to mean "has type which is instance of [type class]", because type classes are often like interfaces, so it's intuitive to think of a concrete thing like an actual Int value as being "compliant" to an interface/type class by virtue of its type implementing whatever is needed to belong to that interface/type class.</p>
  
  <p>Consider the example of wanting to make a single exponentiation function that will work whether it is called with <code>Floating</code> arguments, <code>Num</code>, <code>Integral</code> or whatever, and it works by using the type classes that are implemented by the types of the arguments to select a pre-existing exponentiation function to call.</p>
  
  <p>The function <code>(^)</code> has type <code>(^) :: (Integral b, Num a) =&gt; a -&gt; b -&gt; a</code> and the function <code>(**)</code> has type <code>(**) :: Floating a =&gt; a -&gt; a -&gt; a</code>.</p>
  
  <p>Suppose I want to create a function <code>my_pow</code> that accepts a <code>Num</code> compliant first argument and a <code>Num</code> compliant second argument.</p>
  
  <p>If both arguments are <code>Floating</code> compliant, then it will call <code>(**)</code>; if the second argument is merely <code>Integral</code> compliant, it will call <code>(^)</code>; and any other case will give a pattern matching error.</p>
  
  <p>My naive first try was to treat the type classes like value constructors and try to pattern match within the function definition:</p>
  
  <pre><code>my_pow :: (Num a, Num b) =&gt; a -&gt; b -&gt; a
  my_pow (Floating x) (Floating y) = x ** y
  my_pow x (Integral y) = x ^ y 
  </code></pre>
  
  <p>but this gives the errors:</p>
  
  <pre><code>tmp.hs:25:6: Not in scope: data constructor `Floating'
  
  tmp.hs:25:19: Not in scope: data constructor `Floating'
  
  tmp.hs:26:8: Not in scope: data constructor `Integral'
  </code></pre>
  
  <p>probably meaning that I cannot treat type classes as value constructors, which is not surprising.</p>
  
  <p>But then Googling around for how to pattern-match against particular type class properties of the arguments that are more specific than the type class constraints in the function definition did not yield any clear answers.</p>
  
  <p>What is the preferred way to make this sort of polymorphism -- effectively a dispatch pattern where the function has relaxed type class constraints overall, but then is defined by pattern matching on more specific type class constraints for any of the cases it will dispatch to other other functions.</p>