Skip to content

Instantly share code, notes, and snippets.

@kevgathuku
Forked from animatedlew/len.hs
Created September 17, 2016 11:29
Show Gist options
  • Save kevgathuku/7bb64aaa0324bafcfcbabaff0502244b to your computer and use it in GitHub Desktop.
Save kevgathuku/7bb64aaa0324bafcfcbabaff0502244b 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment