genericLength
is implemented, as of base 4.12, as:
genericLength :: (Num i) => [a] -> i
{-# NOINLINE [1] genericLength #-}
genericLength [] = 0
genericLength (_:l) = 1 + genericLength l
{-# RULES
"genericLengthInt" genericLength = (strictGenericLength :: [a] -> Int);
"genericLengthInteger" genericLength = (strictGenericLength :: [a] -> Integer);
#-}
strictGenericLength :: (Num i) => [b] -> i
strictGenericLength l = gl l 0
where
gl [] a = a
gl (_:xs) a = let a' = a + 1 in a' `seq` gl xs a'
which is basically a foldr
, except that for Int
and Integer
it performs a foldl'
instead.
Why does it not use foldl'
in all cases? Doesn't foldr
build up large thunks for long lists?
Num
implementation. For example one could implement(+)
in such a way that it sometimes only has to look to the first element, and due too lazyness, it could thus terminate the before evaluating the entire list.