Inline functions
XPath 3.0 allows anonymous functions to be created directly in XPath using inline
function expressions. Inline function items can be declared, and used as
arguments to higher-order functions. For example fn:for-each(//employee,
function($e){$e/salary + $e/bonus}).
From XPath 4.0, in inline functions the keyword function may be
abbreviated as fn. (Implemented from Saxon 13.)
The concise syntax is helpful when writing simple callbacks, for example
fold-left($seq, 1, fn($x, $y){$x*$y}) to calculate the product of
a sequence of numbers.
A zero-arity function can be written as, for example,
fn(){doc('abc.xml')//z}.
Focus functions
From XPath 4.0, simple inline functions taking a single argument can be simplified
even further. For example, the expression function{@code} represents
a function that takes a single argument (presumably an element node), and returns
a selected attribute of that node. A simple inline function takes a single
argument of type item()*, and returns any sequence (type
item()*). The function body is evaluated with a singleton focus
based on the supplied argument value.
Simple inline functions are particularly convenient when providing functions as arguments to higher-order functions, many of which accept a single item as their one argument. For example, to sort employees in order of salary, you can write:
sort(//employee, (), fn{xs:decimal(@salary)})Simple inline functions can access externally-defined local variables in the usual way (that is, they have a closure).
The expression function{EXPR} is a syntactic shorthand
for: