Skip to content

Instantly share code, notes, and snippets.

@bahmanm
Created November 20, 2015 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmanm/4121bf991736fd4380bb to your computer and use it in GitHub Desktop.
Save bahmanm/4121bf991736fd4380bb to your computer and use it in GitHub Desktop.
OCaml `List.group_by`
let group_by (f : 'a -> 'b) (ll : 'a list) : ('b, 'a list) Hashtbl.t =
List.fold_left
(fun acc e ->
let grp = f e in
let grp_mems = try Hashtbl.find acc grp with Not_found -> [] in
Hashtbl.replace acc grp (e :: grp_mems);
acc)
(Hashtbl.create 100)
ll;;
@martinklepsch
Copy link

martinklepsch commented Nov 24, 2017

(* Not working (yet) *)
let group_by (f : 'a -> 'b) (ll : 'a list) : ('b, 'a list) Hashtbl.t =
  List.fold
    ll
    ~init:(Hashtbl.create ~size:100)
    ~f:
    (fun acc e ->
       let grp = f e in
       let grp_mems = try Hashtbl.find acc grp with Not_found -> [] in
       Hashtbl.replace acc grp (e :: grp_mems))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment