Skip to content

Instantly share code, notes, and snippets.

@zemm
Last active May 18, 2016 11:58
Show Gist options
  • Save zemm/e475ae3b48d80f5f76bc83241e8b6487 to your computer and use it in GitHub Desktop.
Save zemm/e475ae3b48d80f5f76bc83241e8b6487 to your computer and use it in GitHub Desktop.
Quick, Dirty & Naive GroupBy test hs/elm
module GroupBy exposing (..)
groupBy : List v -> (v -> k) -> List (k, List v)
groupBy items f =
case items of
[] -> []
(x::xs) ->
let key = f x
rest = groupBy xs f
in insertTo rest key x
insertTo : List (k, List v) -> k -> v -> List (k, List v)
insertTo m key value =
case m of
[] -> [(key, [value])]
(x::xs) -> if fst x == key
then [(key, value :: snd x)] ++ xs
else x :: (insertTo xs key value)
module GroupBy where
groupBy :: Eq k => [v] -> (v -> k) -> [(k, [v])]
groupBy [] _ = []
groupBy (x:xs) f =
let key = f x
rest = groupBy xs f
in insertTo rest key x
insertTo :: Eq k => [(k, [v])] -> k -> v -> [(k, [v])]
insertTo [] k v = [(k, [v])]
insertTo (x:xs) key value =
if fst x == key
then [(key, value : snd x)] ++ xs
else x : insertTo xs key value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment