反XML组“收集”不收集

时间:2011-05-10 14:42:41

标签: scala anti-xml

我是从scala-user交叉发布的:

我有以下内容:

object XmlTest {

  import com.codecommit.antixml._

  implicit def toPicker(nodes: Group[Node]): Picker = new Picker(nodes)

  class Picker(nodes: Group[Node]) {
    def pick[A <: Node : ClassManifest]: Group[A] = nodes collect {
      case a if implicitly[ClassManifest[A]].erasure.isInstance(a) => a.asInstanceOf[A]
    }
  }

  def testCollect(elems: Group[Elem]) {
    println("size before collect = " + elems.size)
    val es = elems collect {
      case e if e.name == "c" => println("element name is " + e.name); e
    }
    println("size after collect = " + es.size)
  }

  def main(args: Array[String]) {
    val xml = XML.fromString("<a><b/><c/><d/></a>")

    // this works because <a> has only elements as children
    testCollect(xml.children.asInstanceOf[Group[Elem]])

    // pick filters collection by type
    testCollect(xml.children.pick[Elem])
  }
}

当我跑它时,它打印了以下内容:

[info] size before collect = 3           // size is 3
[info] element name is c                 // element c matches
[info] size after collect = 1              // this is correct
[info] size before collect = 3           // size is the same as the previous case
[info] element name is c                 // element "c" is matched as well
[info] size after collect = 0               // this should be 1

我迷失在这里。发生了什么事?

1 个答案:

答案 0 :(得分:5)

这似乎是Anti-XML中的一个错误。即使没有所有ClassManifest魔法,它也很容易重现:

val xml = <a><b/><c/><d/></a>.anti
xml.children collect { case e => e } collect { case e => e }   // => Group()

问题源于flatMapZipper的实施。考虑到实现的重要性,有些事情肯定是不可思议的,并不奇怪。我将添加一个测试用例,希望今晚得到解决。