E4X: Not as awful as I thought
Long, long ago, I complained about various warts and infelicities in E4X, the ECMAScript extensions for generating and pattern-matching XML documents. It turns out that two of my complaints were not well-founded: sequence-splicing is supported, and programmatic construction of tags is possible.
Firstly (and I’m amazed I didn’t realise this at the time, as I was using it elsewhere), it’s not a problem at all to splice in a sequence of items, in the manner of Scheme’s unquote-splicing; here’s a working solution to the problem I set myself:
function buildItems() {
return <>
<item>Hello</item>
<item>World!</item>
</>;
}
var doc = <mydocument>{buildItems()}</mydocument>;
You can even use real Arrays (which is what I tried and failed to do earlier), by guerilla-patching Array.prototype:
Array.prototype.toXMLList = function () {
var x = <container/>;
for (var i = 0; i < this.length; i++) {
x.appendChild(this[i]);
}
return x.children();
}
function buildItems() {
return [<item>Hello</item>,
<item>World!</item>].toXMLList();
}
var doc = <mydocument>{buildItems()}</mydocument>;
Programmatic construction of tags is done by use of the syntax for plain old unquote, in an unusual position: inside the tag’s angle-brackets:
var tagName = "p";
var doc = <{tagName}>test</{tagName}>;
So in summary, my original expectation that E4X should turn out to be very quasiquote-like wasn’t so far off the mark. It’s enough to get the basics done (ignoring for the minute the problems with namespace prefixes), but it’s still a bit of a bolt-on afterthought; it would have been nice to see it better integrated with the rest of the language.
2 comments May 7th, 2008 tonyg