Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Last active April 16, 2024 14:09
Show Gist options
  • Save animatedlew/8138942 to your computer and use it in GitHub Desktop.
Save animatedlew/8138942 to your computer and use it in GitHub Desktop.
Here are two ways to implement Haskell's length function. One way is to map all the elements to 1, then sum them all up. Another way is to add up each head as you recursively call len' with the tail. The result will be the length of the list.
-- Maps each element to a 1, then sums up all the elements
len :: [a] -> Integer
len = sum . map (\_ -> 1)
-- Adds up all the heads (recursively) until the list is empty
len' :: [a] -> Integer
len' [] = 0
len' (_:xs) = 1 + len' xs
-- Extract into a fold using this technique: [ [] := v, (:) := f ]
-- In the case of length, it requires one more step since we don't
-- use the head of the list in the recursive computation
len'' = foldr (\_ x -> x + 1) 0
Copy link

ghost commented May 20, 2016

len' crashes for large inputs due to stack overflow. Haven't tested len or len''. For those interested, there's some interesting discussion in the comments here about the exercise for implementing length that show how to use tailcalls to avoid overflow. Tailcall version is slow as hell though...I'd love to see how Haskell's length is actually implemented!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment