[Haskell-beginners] Help with types

aditya siram aditya.siram at gmail.com
Thu Apr 23 09:55:51 EDT 2009


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 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.
>
> Cheers,
>
> Daniel.
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090423/4ba489ef/attachment.htm


More information about the Beginners mailing list