Skip to content

Instantly share code, notes, and snippets.

@paldepind
Last active December 28, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paldepind/7511332 to your computer and use it in GitHub Desktop.
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?
-- 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
@paldepind
Copy link
Author

Answer from IRC: The right fold short-circuits due to Haskell being lazy so the two methods are practically equal. Very neat indeed!

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