title: Modify XML in Scala without mutation?
body: <p>I'm trying to replace pieces of XML and need an accumulator along the way. Say I have a fill-in-the-blank question stored as XML like so:</p>
  
  <pre><code>val q = &lt;text&gt;The capitals of Bolivia are &lt;blank/&gt; and &lt;blank/&gt;.&lt;/text&gt;
  </code></pre>
  
  <p>At some point I'm going to want to turn those blanks into HTML input elements and I need to be able to distinguish the first and second so I can check them. (Ignore the fact that, in this case, the two capitals can appear in either order--that's a headache I'll deal with later.)</p>
  
  <p>Thanks to some lovely answers on StackOverflow, I produced the following solution:</p>
  
  <pre><code>import scala.xml._
  import scala.xml.transform._
  
  class BlankReplacer extends BasicTransformer {
    var i = 0
  
    override def transform(n: Node): NodeSeq = n match {
      case &lt;blank/&gt; =&gt; {
        i += 1
        &lt;input name={ "blank.%d".format(i) }/&gt;
      }
      case elem: Elem =&gt; elem.copy(child=elem.child.flatMap(transform _))
      case _ =&gt; n
    }
  }
  </code></pre>
  
  <p>and this works reasonably well. I have to create a <code>new BlankReplacer()</code> each time I want to start re-numbering, but it pretty much works:</p>
  
  <pre><code>scala&gt; new BlankReplacer()(q)
  res6: scala.xml.Node = &lt;text&gt;The capitals of Bolivia are &lt;input name="blank.1"&gt;&lt;/input&gt; and &lt;input name="blank.2"&gt;&lt;/input&gt;.&lt;/text&gt;
  </code></pre>
  
  <p>Here's the question. Is there an easy way to avoid the mutation I have to do each time I replace a <code>&lt;blank/&gt;</code>? What I have doesn't strike me as horrible, but I think this could be cleaner if I weren't creating a new instance of the <code>BlankReplacer</code> class every time I had to convert a question to HTML. I'm sure there's some way to turn this into an accumulator, but I'm not sure how to do it.</p>
  
  <p>Thanks!
  Todd</p>