Last active
August 29, 2015 14:06
-
-
Save kwarrick/161b3b0356d8499430b2 to your computer and use it in GitHub Desktop.
Coalesce a list of overlapping and adjacent start/end tuples.
This file contains hidden or 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
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