leastfixedpoint

E4X: Not as awful as I thought

This page is a mirrored copy of an article originally posted on the (now sadly defunct) LShift blog; see the archive index here.

Wed, 7 May 2008

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.

Comments

On 7 May, 2008 at 1:37 pm, Tom Berger wrote:

I like the term “guerilla-patching”. We usually call it “monkey-patching”. Maybe a good compromise between the two would be to call it “gorilla-patching”!

It would not only be nice to get E4X integrated with the rest of the language, but also with the host. The fact that an E4X tag object is different from a browser’s equivalent document object (when hosted in a browser) is ridiculous, and renders it quite useless for the killer app for this feature.

On 7 May, 2008 at 2:29 pm, tonyg wrote:

Agreed, Tom. Having standardised DOM/E4X integration would be excellent.

WRT monkey-patching - according to wikipedia on the subject, the term actually did start off as guerilla-patch!