Created
March 10, 2022 17:31
-
-
Save htsign/fc66b0e6878f1676d9c176c4a88d655e to your computer and use it in GitHub Desktop.
OCaml `List.group_by`
This file contains 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
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