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