Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created February 18, 2015 12:20
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 shigemk2/c0212100a02e89f374df to your computer and use it in GitHub Desktop.
Save shigemk2/c0212100a02e89f374df to your computer and use it in GitHub Desktop.
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