Skip to content

Instantly share code, notes, and snippets.

@kwarrick
Last active August 29, 2015 14:06
Show Gist options
  • Save kwarrick/161b3b0356d8499430b2 to your computer and use it in GitHub Desktop.
Save kwarrick/161b3b0356d8499430b2 to your computer and use it in GitHub Desktop.
Coalesce a list of overlapping and adjacent start/end tuples.
open Core.Std
(**
* Coalesce a list of overlapping and adjacent start/end tuples.
*
* let ranges = [(2,3); (1,2); (5,11); (4,10); (3,3)];;
* coalesce_ranges ranges;;
* - : (int * int) list = [(1, 11)]
**)
let coalesce_ranges ?(cmp=compare) ranges =
let sorted = List.sort cmp ranges in
let coalesce' acc r =
match acc, r with
| [], _ -> [r]
| (a,b) :: tl, (x,y) ->
if (b + 1) >= x then (a, max b y) :: tl
else r :: acc
in
List.fold_left ~f:coalesce' ~init:[] sorted
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment