Given a list of pairs of integers that represent closed numeric intervals, I need to output a list of intervals where the adjacent intervals are merged together. The code assumes that the intervals do not overlap and that a <= b
in all pairs (a, b)
.
Intervals (a,b)
and (c,d)
are adjacent if b + 1 == c
.
merge [] = []
merge [x] = [x]
merge ((a, b):(c, d):xs)
| b + 1 == c = merge ((a, d):xs)
| otherwise = (a, b):(merge ((c, d):xs))
Maybe I can simplify this and use fold
or something like that? Also, would converting this to a tail recursive version make sense here?