Last active
April 16, 2024 14:09
-
-
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.
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
len'
crashes for large inputs due to stack overflow. Haven't testedlen
orlen''
. For those interested, there's some interesting discussion in the comments here about the exercise for implementinglength
that show how to use tailcalls to avoid overflow. Tailcall version is slow as hell though...I'd love to see how Haskell'slength
is actually implemented!