Why Integral makes a function much slower than Int?

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Why Integral makes a function much slower than Int?

Jaakko Luttinen
Hi all,

I implemented a simple function to calculate the length of a list.
However, I noticed that the speed of the function changes significantly
if I make I minor change to the type signature but keep the
implementation the same otherwise. I was wondering why this happens.

Contents of mylength.hs:

module MyLength where

-- Here is the first implementation:

myLength :: Integral n => [a] -> n
myLength xs = run xs 0
     run [] n = n
     run (_:ys) n = run ys (n+1)

-- Then, the other implementation just fixes the return type without
-- modifying the actual implementation:

myLength' :: [a] -> Int
myLength' = myLength

When I compile these implementations with:

ghc -dynamic -O2 mylength.hs

Then, launch ghci:

ghci -fobject-code

And in ghci:

:load mylength.hs
:set +s

(myLength [1..10000000]) :: Int
(2.30 secs, 1,612,737,944 bytes)

(myLength' [1..10000000]) :: Int
(0.38 secs, 720,077,536 bytes)

So, the first implementation is much worse, although I've fixed the
return type to Int too.

What's going on? Does this mean one shouldn't use Integral but Int
instead most of the time?

Thanks for help!

Beginners mailing list
[hidden email]