title: Recursively accumulate elements of collection
body: <p>I have a collection of elements with an integer range such as</p>
  
  <pre><code>case class Element(id: Int, from: Int, to: Int)
  val elementColl: Traversable[Element]
  </code></pre>
  
  <p>and I want to accumulate them into</p>
  
  <pre><code>case class ElementAcc(ids: List[Int], from: Int, to: Int)
  </code></pre>
  
  <p>according to the following algorithm:</p>
  
  <ol>
  <li>Take one <code>Element</code> from my <code>elementColl</code> and use it to create a new <code>ElementsAcc</code> which has the same from/to as the <code>Element</code> taken.</li>
  <li>Iterate over remaining elements in <code>elementColl</code> to look for an <code>Element</code> that has an overlapping integer range with our <code>ElementAcc</code>.</li>
  <li>If one is found, add it to <code>ElementAcc</code> and expand the integer range of <code>ElementAcc</code> to include the range of the new <code>Element</code></li>
  <li>If none is found, repeat the process above on the remaining elements of <code>elementColl</code> that have not yet been assigned to an <code>ElementAcc</code></li>
  </ol>
  
  <p>This should result in collection of <code>ElementAcc</code>'s. While just recursively adding elements to an accumulator seems easy enough, I don't know how to handle the shrinking size of <code>elementColl</code> so that I don't add the same <code>Element</code> to multiple <code>ElementAcc</code>'s</p>
  
  <p><strong>Edit:</strong> I think I was unclear regarding the extension of the range. So let my clarify this on an example:</p>
  
  <p>My accumulator currently has a range from 1 to 5. An Element with a range from 6 to 8 does not overlap with the accumulator range and thus will not be included. An Element with a range of 4 to 7 does overlap, will be included and the resulting accumulator has a range from 1 to 7.</p>