Last active
December 28, 2015 13:59
-
-
Save paldepind/7511332 to your computer and use it in GitHub Desktop.
Two implementations of a `findKey` function from Learn You a Haskell for Great Good. One uses explicit recursion the other a fold. The book recommends using fold for readability. But wouldn't using recursion be more efficient since the recursion halts as soon as an element is found?
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
-- Recursion | |
findKey :: (Eq k) => k -> [(k,v)] -> Maybe v | |
findKey key [] = Nothing | |
findKey key ((k,v):xs) = if key == k | |
then Just v | |
else findKey key xs | |
-- Fold | |
findKey :: (Eq k) => k -> [(k,v)] -> Maybe v | |
findKey key = foldr (\(k,v) acc -> if key == k then Just v else acc) Nothin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer from IRC: The right fold short-circuits due to Haskell being lazy so the two methods are practically equal. Very neat indeed!