Skip to content

Instantly share code, notes, and snippets.

@shigemk2 shigemk2/findKey.hs
Created Feb 18, 2015

Embed
What would you like to do?
findKey :: (Eq k) => k -> [(k, v)] -> Maybe v
-- 該当者なしならNothingでエラーハンドリング
findKey key [] = Nothing
findKey key ((k,v):xs)
| key == k = Just v
| otherwise = findKey key xs
-- 該当者なしならエラーになるやつ
findKey' :: (Eq k) => k -> [(k, v)] -> v
findKey' key xs = snd . head . filter (\(k, v) -> key == k) $ xs
-- 畳み込みでどうにかしたい
findKey'' :: (Eq k) => k -> [(k, v)] -> Maybe v
findKey'' key xs = foldr
(\(k, v) acc -> if key == k then Just v else acc)
Nothing xs
phoneBook =
[("betty", "555-2938")
,("bonnie", "452-2928")
,("patsy", "493-2928")
,("lucille", "205-2928")
,("wendy", "939-8282")
,("penny", "853-2492")
]
main = do
print $ findKey "penny" phoneBook
print $ findKey "betty" phoneBook
print $ findKey "wilma" phoneBook -- Nothing
print $ findKey' "penny" phoneBook
print $ findKey' "betty" phoneBook
-- print $ findKey' "wilma" phoneBook -- Nothing -- 該当者なしでエラー
print $ findKey'' "penny" phoneBook
print $ findKey'' "betty" phoneBook
print $ findKey'' "wilma" phoneBook -- Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.