title: Haskell types frustrating a simple 'average' function
body: <p>I'm playing around with beginner Haskell, and I wanted to write an average function.  It seemed like the simplest thing in the world, right?</p>
  
  <p>Wrong.</p>
  
  <p>It seems like Haskell's type system forbids average from working on a generic numeric type - I can get it to work on a list of Integrals, or an list of Fractionals, but not both.</p>
  
  <p>I want:</p>
  
  <pre><code>average :: (Num a, Fractional b) =&gt; [a] -&gt; b
  average xs = ...
  </code></pre>
  
  <p>But I can only get:</p>
  
  <pre><code>averageInt :: (Integral a, Fractional b) =&gt; [a] -&gt; b
  averageInt xs = fromIntegral (sum xs) / fromIntegral (length xs)
  </code></pre>
  
  <p>or </p>
  
  <pre><code>averageFrac :: (Fractional a) =&gt; [a] -&gt; a
  averageFrac xs = sum xs / fromIntegral (length xs)
  </code></pre>
  
  <p>and the second one seems to work.  Until I try to pass a variable.</p>
  
  <pre><code>*Main&gt; averageFrac [1,2,3]
  2.0
  *Main&gt; let x = [1,2,3]
  *Main&gt; :t x
  x :: [Integer]
  *Main&gt; averageFrac x
  
  &lt;interactive&gt;:1:0:
      No instance for (Fractional Integer)
        arising from a use of `averageFrac ' at &lt;interactive&gt;:1:0-8
      Possible fix: add an instance declaration for (Fractional Integer)
      In the expression: average x
      In the definition of `it': it = averageFrac x
  </code></pre>
  
  <p>Apparently, Haskell is really picky about its types.  That makes sense.  But not when they could both be [Num]</p>
  
  <p>Am I missing an obvious application of RealFrac?</p>
  
  <p>Is there way to coerce Integrals into Fractionals that doesn't choke when it gets a Fractional input?</p>
  
  <p>Is there some way to use <code>Either</code> and <code>either</code> to make some sort of polymorphic average function that would work on any sort of numeric array?</p>
  
  <p>Does Haskell's type system outright forbid this function from ever existing?</p>
  
  <p>Learning Haskell is like learning Calculus.  It's really complicated and based on mountains of theory, and sometimes the problem is so mindbogglingly complex that I don't even know enough to phrase the question correctly, so any insight will be warmly accepted.</p>
  
  <p>(Also, footnote: this is based off a homework problem. Everybody agrees that averageFrac, above, gets full points, but I have a sneaking suspicion that there is a way to make it work on both Integral AND Fractional arrays)</p>