Sometimes it’s easiest to so something recursively:
(define (combine-ranges a b)<br></br>(cons (min (car a) (car b))<br></br>(max (car a) (cdr b))))<br></br><br></br>(define (combine-selection-ranges-aux range ranges sorted)<br></br>(if (ranges)<br></br>(let ((next-range (car ranges))<br></br>(rest (cdr ranges)))<br></br>(if (selections-overlap? range next-range)<br></br>(combine-selection-ranges-aux (car rest)<br></br>(cdr rest)<br></br>(cons (combine-ranges range<br></br>next-range)<br></br>sorted)))<br></br>(combine-selection-ranges-aux next-range rest<br></br>(cons range sorted))))<br></br>(cons range sorted))<br></br><br></br>(define (combine-selection-ranges ranges)<br></br>(combine-selection-ranges-aux (car ranges) (cdr ranges)))<br></br>
But I haven’t debugged this yet and I think I may have missed a case. :-)