length
counts the occurences of elements a
in a foldable structure t a
.
ghci> length [7, 2, 9] -- t ~ []
3
ghci> length (Right 'a') -- t ~ Either e
1 -- 'Either e a' may contain zero or one 'a'
ghci> length (Left "foo") -- t ~ Either String
0
ghci> length (3, True) -- t ~ (,) Int
1 -- '(c, a)' always contains exactly one 'a'
length
is defined as being equivalent to:
class Foldable t where
-- ...
length :: t a -> Int
length = foldl' (\c _ -> c+1) 0
Note that this return type Int
restricts the operations that can be performed on values obtained by calls to the length
function. fromIntegral
is a useful function that allows us to deal with this problem.