Skip to content

Instantly share code, notes, and snippets.

@nickserv
Last active February 22, 2022 17:17
Show Gist options
  • Save nickserv/9987910 to your computer and use it in GitHub Desktop.
Save nickserv/9987910 to your computer and use it in GitHub Desktop.
A lookup' function for Haskell that does the opposite of lookup in Prelude
-- | lookup' @key assocs@ looks up a value in an association list. While lookup
-- finds a tuple where the first value matches and returns the second, lookup'
-- does the opposite.
lookup' :: (Eq b) => b -> [(a,b)] -> Maybe a
lookup' _ [] = Nothing
lookup' key ((x,y):xys)
| key == y = Just x
| otherwise = lookup' key xys
-- Prints "Just 2".
main = print $ lookup' "two" [(1,"one"), (2,"two"), (3,"three")]
@aishstha
Copy link

Nice!

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