- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Change in matching behaviour?
Mon, 2010-06-21, 15:17
Hi,
I've come back to some old (circa 2.8.rc1) code and the following no longer seems to work:
scala> import xml._
import xml._
scala> val good = <good>something</good>
good: scala.xml.Elem = <good>something</good>
scala> val bad = <bad></bad>
bad: scala.xml.Elem = <bad></bad>
scala> def f(node: Node) = node match {
| case Elem(_, name, _, _, _) => name
| case _ => "didn't match"
| }
f: (node: scala.xml.Node)String
scala> f(good)
res0: String = good
scala> f(bad)
res1: String = didn't match
scala> val bad2 = <bad />
bad2: scala.xml.Elem = <bad></bad>
scala> f(bad2)
res2: String = didn't match
I'm pretty sure this worked properly before. Can someone confirm whether this behaviour is intended + I'll file a bug if needed.
I've come back to some old (circa 2.8.rc1) code and the following no longer seems to work:
scala> import xml._
import xml._
scala> val good = <good>something</good>
good: scala.xml.Elem = <good>something</good>
scala> val bad = <bad></bad>
bad: scala.xml.Elem = <bad></bad>
scala> def f(node: Node) = node match {
| case Elem(_, name, _, _, _) => name
| case _ => "didn't match"
| }
f: (node: scala.xml.Node)String
scala> f(good)
res0: String = good
scala> f(bad)
res1: String = didn't match
scala> val bad2 = <bad />
bad2: scala.xml.Elem = <bad></bad>
scala> f(bad2)
res2: String = didn't match
I'm pretty sure this worked properly before. Can someone confirm whether this behaviour is intended + I'll file a bug if needed.
Mon, 2010-06-21, 22:37
#2
Re: Change in matching behaviour?
On Mon, Jun 21, 2010 at 03:17:30PM +0100, Alec Zorab wrote:
> I've come back to some old (circa 2.8.rc1) code and the following no
> longer seems to work:
Your transcript does not reveal to me what "work" means. I can tell you
that in terms of pattern matching, Elem hasn't changed interestingly
since 2.7:
// 2.7
object Elem {
def unapplySeq(n:Node) = if(n.isInstanceOf[SpecialNode]||n.isInstanceOf[Group]) None else
Some(Tuple5(n.prefix,n.label,n.attributes,n.scope,n.child))
}
// 2.8
object Elem {
def unapplySeq(n: Node) = n match {
case _: SpecialNode | _: Group => None
case _ => Some((n.prefix, n.label, n.attributes, n.scope, n.child))
}
}
And 2.7, beta1, rc1, and current trunk all do the same thing with your
example. So my first question is what has changed, and with that in
hand I can probably tell you if it's expected.
I've been bitten by this too, but not in the context of XML, as I'll explain below...
This element has a child.
This element has no child.
This matches Elems with one child. :)
If you want to match any number of children, replace the last "_" with "_*" . All part of the magic of unapplySeq. :)
-0xe1a