Skip to content

Instantly share code, notes, and snippets.

@dasch
Created October 28, 2015 20:06
Show Gist options
  • Save dasch/26abc38d242fadd06fcb to your computer and use it in GitHub Desktop.
Save dasch/26abc38d242fadd06fcb to your computer and use it in GitHub Desktop.
counts : List Int -> Dict Int Int
counts items =
List.map (\x -> Dict.singleton x 1) items
|> List.foldr (merge combine) Dict.empty
combine : Maybe Int -> Maybe Int -> Int
combine a b =
case (a, b) of
(Just a', Just b') -> a' + b'
(Just a', Nothing) -> a'
(Nothing, Just b') -> b'
(Nothing, Nothing) -> 0
merge : (Maybe Int -> Maybe Int -> Int) -> Dict Int Int -> Dict Int Int -> Dict Int Int
merge f d1 d2 =
Dict.union d1 d2
|> Dict.keys
|> List.map (\k -> (k, Dict.get k d1, Dict.get k d2))
|> List.map (\(k, v1, v2) -> (k, f v1 v2))
|> Dict.fromList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment