XPath Reference

Higher-order Functions (3.1)

XPath 3.1 treats functions as values. You can pass inline functions to built-ins like for-each, filter, fold-left, and sort to map, prune, reduce, and reorder sequences without writing a FLWOR. These six are the core of the higher-order kit — once they click, a lot of awkward 1.0 patterns collapse into one-liners.

for-each(seq, fn)

Map a function over a sequence

Applies a single-argument function to every item in the sequence and returns the concatenated results. The functional cousin of the 'for $x in S return …' expression — often shorter when you just need to transform each item independently.

filter(seq, pred)

Keep items matching a predicate

Returns the items for which the supplied function returns true. Equivalent to a predicate, but using a function value, which means the predicate can be passed around as data and reused across multiple calls.

fold-left(seq, zero, fn)

Left-fold (reduce) a sequence

Reduces a sequence to a single value by repeatedly combining an accumulator with each item from left to right. The 'zero' argument is the starting accumulator. Use it for sums, concatenations, or any incremental aggregation that a single sum()/string-join() can't express.

fold-right(seq, zero, fn)

Right-fold (reduce) a sequence

Like fold-left, but the combining function sees items from right to left. The difference matters when the operation is not associative — for example, building a nested structure that should grow from the tail.

for-each-pair(s1, s2, fn)

Zip two sequences

Walks two sequences in parallel, calling the two-argument function on each (item-from-s1, item-from-s2) pair. The result stops at the shorter sequence. Perfect for combining matched lists — names with emails, titles with artists — without index juggling.

sort(seq, coll?, key?)

Sort by value or key function

Sorts a sequence. With one argument it sorts by the atomized value. With three arguments, the second is a collation (often () for default) and the third is a key function returning the value to sort by — for example sort(//album, (), function($a) { number($a/@year) }).

← Back to full reference