-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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