Created
October 20, 2015 04:53
-
-
Save motokiee/b809ea275eac8bfff5f7 to your computer and use it in GitHub Desktop.
きょうはData.Mapに触れましたよ #CodePiece
This file contains hidden or 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
| import qualified Data.Map as Map | |
| import Data.Char | |
| phoneBook = | |
| [("betty", "555-2938"), | |
| ("betty", "342-2492"), | |
| ("bonnie", "452-2928"), | |
| ("pasty", "493-2928"), | |
| ("pasty", "943-2928"), | |
| ("pasty", "827-9162"), | |
| ("lucille", "205-2928"), | |
| ("wendy", "939-8282"), | |
| ("penny", "853-2492"), | |
| ("penny", "555-2111") | |
| ] | |
| 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 [] = Nothing | |
| findKey' key ((k,v):xs) | |
| | key == k = Just v | |
| | otherwise = findKey' key 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' :: Map.Map String String | |
| phoneBook' = Map.fromList $ | |
| [("betty", "555-2938"), | |
| ("bonnie", "452-2928"), | |
| ("pasty", "493-2928"), | |
| ("lucille", "205-2928"), | |
| ("wendy", "939-8282"), | |
| ("penny", "853-2492") | |
| ] | |
| string2digits :: String -> [Int] | |
| string2digits = map digitToInt . filter isDigit | |
| phoneBookToMap :: (Ord k) => [(k,String)] -> Map.Map k String | |
| phoneBookToMap xs = Map.fromListWith add xs | |
| where add number1 number2 = number1 ++ ", " ++ number2 | |
| phoneBookToMap' :: (Ord k) => [(k,a)] -> Map.Map k [a] | |
| phoneBookToMap' xs = Map.fromListWith (++) $ map (\(k,v) -> (k,[v])) xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment