Skip to content

Instantly share code, notes, and snippets.

@shamrin
Last active September 26, 2016 03:09
Show Gist options
  • Save shamrin/d8666c94b994b8d5d862 to your computer and use it in GitHub Desktop.
Save shamrin/d8666c94b994b8d5d862 to your computer and use it in GitHub Desktop.
module Group where

import List.Extra exposing (span)

countingGroupBy : (a -> b) -> List a -> List (b, Int)
countingGroupBy key xs' =
  let
    eq a b = key a == key b

  in
    case xs' of
      [] ->
        []

      (x::xs) ->
        let
          (ys, zs) = span (eq x) xs
        in
          (key x, (List.length ys) + 1) :: countingGroupBy key zs

countingGroup = countingGroupBy identity
$ elm-package install --yes circuithub/elm-list-extra
$ elm-repl
> import Group
> [ { age = 10, name = "Ralf" }, { age = 10, name = "Peter" }, { age = 12, name = "Peter" } ] |> List.sortBy .age |> Group.countingGroupBy .age
[(10,2),(12,1)] : List ( number, Int )
> ["a", "b", "a", "d", "d", "c"] |> List.sort |> Group.countingGroup
[("a",2),("b",1),("c",1),("d",2)] : List ( String, Int )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment