[Haskell-beginners] Help with types
aditya.siram at gmail.com
Thu Apr 23 09:55:51 EDT 2009
There is a chapter in Real World Haskell  devoted to this exact question
on this exact piece of code.
On Thu, Apr 23, 2009 at 8:52 AM, Daniel Carrera <
daniel.carrera at 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.
> Beginners mailing list
> Beginners at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners