
There is a chapter in Real World Haskell [1] devoted to this exact question on this exact piece of code. hth, -deech [1] http://book.realworldhaskell.org/read/profiling-and-optimization.html On Thu, Apr 23, 2009 at 8:52 AM, Daniel Carrera < daniel.carrera@theingots.org> wrote:
Daniel Fischer wrote:
Try explicitly converting the length to the appropriate type:
average xs = sum xs / fromIntegral (length xs)
Thanks. Could you help me understand what's happening?
1. length returns Int. 2. sum returns Num. 3. (/) wants Fractional.
It looks like (/) is happy with Num but doesn't like Int. This surprises me. I would have thought that Fractional is a kind of Num and Int is a kind of Fractional, so a function that expects Fractional would be happy with an Int but maybe not with a Num. But clearly that's not the way it works.
'fromIntegral' converts Int to Num. So obviously, Num is good and Int is bad. But I don't really get why.
will yield a working (albeit inefficient)
average :: Fractional a => [a] -> a
Why is it inefficient? How would you make it efficient?
Thanks for the help.
Cheers,
Daniel. _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners