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
Daniel Fischer wrote:Thanks. Could you help me understand what's happening?
Try explicitly converting the length to the appropriate type:
average xs = sum xs / fromIntegral (length xs)
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.Why is it inefficient? How would you make it efficient?
will yield a working (albeit inefficient)
average :: Fractional a => [a] -> a
Thanks for the help.
Cheers,
Daniel.
_______________________________________________
Beginners mailing list
Beginners@haskell.org
http://www.haskell.org/mailman/listinfo/beginners