[Haskell-beginners] Help with types

Daniel Carrera daniel.carrera at theingots.org
Thu Apr 23 09:52:00 EDT 2009


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.


More information about the Beginners mailing list