Re: [xsl] HOF in XPath/XSLT 2.1?

Subject: Re: [xsl] HOF in XPath/XSLT 2.1?
From: Pavel Minaev <int19h@xxxxxxxxx>
Date: Tue, 13 Oct 2009 15:25:41 -0700
On Tue, Oct 13, 2009 at 2:30 PM, Michael Kay <mike@xxxxxxxxxxxx> wrote:
> The XSL WG has discussed this and is I think very likely to include
> higher-order functions in XSLT 2.1 and XPath 2.1, but the exact details are
> not yet decided (and indeed, the formal decision to go ahead is not yet
> made).

Very interesting, and somewhat unexpected (I thought it would be
considered an overly powerful and complicated feature for XPath, to be
honest). I definitely hope it gets in, because this would have one
curious side effect specifically for XPath: it will finally become
possible to bind a variable to a sequence from within XPath
expression, same as what "let" can do in XQuery. Assuming the same
syntax as what is currently seen in Saxon:

   function($xs){ ... }(1 to 10)

At present, the only variable-binding constructs are "for", "some" and
"every", and they all expand sequences, while at times it can be very
convenient to refer to the same sequence, itself produced by a fairly
complicated XPath expression, more than once. It's a pity "let" wasn't
lifted from XQuery to XPath originally when "for" was, but I could
live with HOF workaround for when it's really needed, ugly-looking as
it may be.

> When I looked at this I was initially inclined to think that unnamed/local
> xsl:function declarations would be appropriate, but when I tried to work out
> a few use cases, it wasn't clear that they added much. That's because local
> functions are most commonly needed as an argument to a function call, which
> is in XPath territory; and if the local function has to be bound to a
> variable before it can be used, then you gain very little over defining a
> global named function. There's a possibility that a local xsl:function could
> be useful for returning a constructed function as the result of a function,
> but I'm not convinced.

So far as I can see, the main reasoning would be to allow closures
that use XSLT constructs. Since XPath itself is fairly limited, having
things like <xsl:sort>, <xsl:for-each-group> and <xsl:analyze-string>
can be convenient. One can expose them to XPath indirectly via
<xsl:function>, but that means losing the convenience of automatic
variable capturing of inline functions...

A minor readability-improving side effect would be the ability to
limit the scope of function definitions specifically to blocks where
they're used, similar to long-standing practice in e.g. Pascal and
derived languages.

That said, having the ability to define functions in XPath and bind
them to XSLT variables would still cover vast majority of real-life
scenarios, so personally, I would be quite happy with that alone, and
very much hope that this feature gets into the final spec.

Current Thread