Last active
February 22, 2022 17:17
-
-
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
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
-- | 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")] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!