Skip to content

Instantly share code, notes, and snippets.

@xandkar
Created April 26, 2014 15:28
Show Gist options
  • Save xandkar/11322931 to your computer and use it in GitHub Desktop.
Save xandkar/11322931 to your computer and use it in GitHub Desktop.
open Core_kernel.Std
let group_by l f =
List.fold_left l ~init:[] ~f:(fun groups x ->
let y = f x in
let group =
match List.Assoc.find groups y with
| Some xs -> x :: xs
| None -> [x]
in
List.Assoc.add groups y group
)
@xandkar
Copy link
Author

xandkar commented Apr 26, 2014

  group_by [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] (fun x -> x mod 2);;
- : (int, int list) Core.Std.List.Assoc.t =
[(0, [10; 8; 6; 4; 2]); (1, [9; 7; 5; 3; 1])]
# 

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