Skip to content

Instantly share code, notes, and snippets.

@htsign
Created March 10, 2022 17:31
Show Gist options
  • Save htsign/fc66b0e6878f1676d9c176c4a88d655e to your computer and use it in GitHub Desktop.
Save htsign/fc66b0e6878f1676d9c176c4a88d655e to your computer and use it in GitHub Desktop.
OCaml `List.group_by`
module List = struct
include Stdlib.List
let group_by (projection : 'a -> 'key) (xs : 'a list) : ('key * 'a list) list =
let pairs = xs |> List.map (fun x -> projection x, x) in
let rec aux acc = function
| [] -> acc |> List.rev
| ((k, _) :: _) as xs ->
let ys, zs = xs |> List.partition (fun t -> fst t = k) in
aux ((k, ys |> List.map snd) :: acc) zs
in
aux [] pairs
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment