Haskell Length function implementation

Viewed 5190

I am learning Haskell programming, and I am trying to understand how lists work, hence I attempted writing two possible length functions:

myLength :: [a] -> Integer
myLength  = foldr (\x -> (+) 1) 0

myLength1 :: [a] -> Integer
myLength1 []     = 0
myLength1 (x:xs) = (+1) (myLength1 xs)

Which one is better?

From my point of view, myLength1 is much easier to understand, and looks natural for operating on lists.

On the other hand, myLength is shorter and it does not use recursion; does this imply myLength runs faster than myLength1?

3 Answers

Using foldr, it can be implemented as:

length' xs = foldr (\_ n -> 1 + n) 0 xs

Explanation:

The lambda function (\_ x -> n + 1) will increment the accumulator by one every time there is an element. For instance:

lenght' [1..4]

will be applied as: 1 + ( 1 + ( 1 + ( 1 + 0)))

Recall that foldr is defined like this:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f v [] = v
foldr f v (x:xs) = f x (foldr f v xs)
Related