View Old View New View Both View Only Previous Next

This draft contains only sections that have differences from the version that it modified.

W3C

XPath and XQuery Functions and Operators 4.0

W3C Editor's Draft 23 February 2026

This version:
https://qt4cg.org/specifications/xpath-functions-40/
Latest version of XPath and XQuery Functions and Operators 4.0:
https://qt4cg.org/specifications/xpath-functions-40/
Most recent Recommendation of XPath and XQuery Functions and Operators:
https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/
Editor:
Michael Kay, Saxonica <http://www.saxonica.com/>

Please check the errata for any errors or issues reported since publication.

See also translations.

This document is also available in these non-normative formats: Specification in XML format and XML function catalog.


Abstract

This document defines constructor functions, operators, and functions on the datatypes defined in [XML Schema Part 2: Datatypes Second Edition] and the datatypes defined in [XQuery and XPath Data Model (XDM) 3.1]. It also defines functions and operators on nodes and node sequences as defined in the [XQuery and XPath Data Model (XDM) 3.1]. These functions and operators are defined for use in [XML Path Language (XPath) 4.0] and [XQuery 4.0: An XML Query Language] and [XSL Transformations (XSLT) Version 4.0] and other related XML standards. The signatures and summaries of functions defined in this document are available at: http://www.w3.org/2005/xpath-functions/.

A summary of changes since version 3.1 is provided at G Changes since 3.1.

Status of this Document

This version of the specification is work in progress. It is produced by the QT4 Working Group, officially the W3C XSLT 4.0 Extensions Community Group. Individual functions specified in the document may be at different stages of review, reflected in their History notes. Comments are invited, in the form of GitHub issues at https://github.com/qt4cg/qtspecs.

Dedication

The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).


17 Higher-order functions

17.2 Basic higher-order functions

The following functions take function items as an argument.

FunctionMeaning
fn:applyMakes a dynamic call on a function with an argument list supplied in the form of an array.
fn:chainApplies a sequence of functions starting with an initial input.
fn:do-untilProcesses a supplied value repeatedly, continuing when some condition is false, and returning the value that satisfies the condition.
fn:everyReturns true if every item in the input sequence matches a supplied predicate.
fn:filterReturns those items from the sequence $input for which the supplied function $predicate returns true.
fn:fold-leftProcesses the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:fold-rightProcesses the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:for-eachApplies the function item $action to every item from the sequence $input in turn, returning the concatenation of the resulting sequences in order.
fn:for-each-pairApplies the function item $action to successive pairs of items taken one from $input1 and one from $input2, returning the concatenation of the resulting sequences in order.
fn:highestReturns those items from a supplied sequence that have the highest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn:index-whereReturns the positions in an input sequence of items that match a supplied predicate.
fn:lowestReturns those items from a supplied sequence that have the lowest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn:partial-applyPerforms partial application of a function item by binding values to selected arguments.
fn:partitionPartitions a sequence of items into a sequence of non-empty arrays containing the same items, starting a new partition when a supplied condition is true.
fn:scan-leftProduces the sequence of successive partial results from the evaluation of fn:fold-left with the same arguments.
fn:scan-rightProduces the sequence of successive partial results from the evaluation of fn:fold-right with the same arguments.
fn:someReturns true if at least one item in the input sequence matches a supplied predicate.
fn:sortSorts a supplied sequence, based on the value of a number of sort keys supplied as functions.
fn:sort-withSorts a supplied sequence, according to the order induced by the supplied comparator functions.
fn:subsequence-whereReturns a contiguous sequence of items from $input, with the start and end points located by applying predicates.
fn:take-whileReturns items from the input sequence prior to the first one that fails to match a supplied predicate.
fn:transitive-closureReturns all the nodes reachable from a given start node by applying a supplied function repeatedly.
fn:while-doProcesses a supplied value repeatedly, continuing while some condition remains true, and returning the first value that does not satisfy the condition.

With all these functions, if the caller-supplied function fails with a dynamic error, this error is propagated as an error from the higher-order function itself.

17.2.6 fn:fold-left

Summary

Processes the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.

Signature
fn:fold-left(
$inputas item()*,
$accuminitas item()*,
$actionas fn(item()*, item()) as item()*
) as item()*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

If $input is empty, the function returns $accuminit.

If $input contains at least one item, the function calls $action($accuminit, $input[1]), returning a value A1.

If $input contains a second item, the function then calls $action(A1, $input[2]), returning A2; to process the nth item it calls $action(An-1, $input[N]).

This continues in the same way until the end of the $input sequence; the final result is the result of the last call on $action.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare function fold-left(
  $input  as item()*,
  $accum   as item()*,
  $action as function(item()*, item()) as item()*
) as item()* {
  if (empty($input)) 
  then $accum
  else fold-left(tail($input), $action($accum, head($input)), $action)
};
declare function fold-left(
  $input  as item()*,
  $init   as item()*,
  $action as function(item()*, item()) as item()*
) as item()* {
  if (empty($input)) 
  then $init
  else fold-left(tail($input), $action($init, head($input)), $action)
};
Error Conditions

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $action cannot be applied to two arguments, where the first argument is either the value of $accuminit or the result of a previous application of $action, and the second is any single item from the sequence $input.

Notes

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It typically takes a function that operates on a pair of values, and applies it repeatedly, with an accumulated result as the first argument, and the next item in the sequence as the second argument. The accumulated result is initially set to the value of the $accuminit argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

Unlike other functions that apply a user-supplied callback function to successive items in a sequence, this function does not supply the current position to the callback function as an optional argument. If positional information is required, this can be achieved by first forming the sequence $input ! {'position': position(), 'item': .} and then applying the fn:fold-left function to this sequence.

Examples
Expression:
fold-left(
  1 to 5,
  0,
  fn($a, $b) { $a + $b }
)
Result:
15

(This returns the sum of the items in the sequence).

Expression:
fold-left(
  (2, 3, 5, 7),
  1,
  fn($a, $b) { $a * $b }
)
Result:
210

(This returns the product of the items in the sequence).

Expression:
fold-left(
  (true(), false(), false()),
  false(),
  fn($a, $b) { $a or $b }
)
Result:
true()

(This returns true if any item in the sequence has an effective boolean value of true).

Expression:
fold-left(
  (true(), false(), false()),
  false(),
  fn($a, $b) { $a and $b }
)
Result:
false()

(This returns true only if every item in the sequence has an effective boolean value of true).

Expression:
fold-left(
  1 to 5,
  (),
  fn($a, $b) { $b, $a }
)
Result:
5, 4, 3, 2, 1

(This reverses the order of the items in a sequence).

Expression:
fold-left(
  1 to 5,
  "",
  concat(?, ".", ?)
)
Result:
".1.2.3.4.5"
Expression:
fold-left(
  1 to 5,
  "$z",
  concat("$f(", ?, ", ", ?, ")")
)
Result:
"$f($f($f($f($f($z, 1), 2), 3), 4), 5)"
Expression:
fold-left(
  1 to 5,
  {},
  fn($map, $n) { map:put($map, $n, $n * 2) }
)
Result:
{ 1: 2, 2: 4, 3: 6, 4: 8, 5: 10 }

17.2.7 fn:fold-right

Changes in 4.0  

  1. The $action callback function accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Processes the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.

Signature
fn:fold-right(
$inputas item()*,
$accuminitas item()*,
$actionas fn(item(), item()*) as item()*
) as item()*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

If $input is empty, the function returns $accuminit.

Let In be the last item in $input, and let An be $accuminit. The function starts by calling $action(In, $accuminit), producing a result An-1.

If there is a previous item, In-1, the function then calls $action(In-1, An-1), producing the result An-2.

This continues in the same way until the start of the $input sequence is reached; the final result is the value A0.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare function fold-right(
  $input  as item()*,
  $accum   as item()*,
  $action as function(item(), item()*) as item()*
) as item()* {
  if (empty($input))
  then $accum
  else $action(head($input), fold-right(tail($input), $accum, $action))
};
declare function fold-right(
  $input  as item()*,
  $init   as item()*,
  $action as function(item(), item()*) as item()*
) as item()* {
  if (empty($input))
  then $init
  else $action(head($input), fold-right(tail($input), $init, $action))
};
Error Conditions

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $action cannot be applied to two arguments, where the first argument is any item in the sequence $input, and the second is either the value of $accuminit or the result of a previous application of $action.

Notes

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It takes a function that operates on a pair of values, and applies it repeatedly, with the next item in the sequence as the first argument, and the result of processing the remainder of the sequence as the second argument. The accumulated result is initially set to the value of the $accuminit argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

In cases where the function performs an associative operation on its two arguments (such as addition or multiplication), fn:fold-right produces the same result as fn:fold-left.

Unlike other functions that apply a user-supplied callback function to successive items in a sequence, this function does not supply the current position to the callback function as an optional argument. If positional information is required, this can be achieved by first forming the sequence $input ! {'position': position(), 'item': .} and then applying the fn:fold-right function to this sequence.

Examples
Expression:
fold-right(
  1 to 5,
  0,
  fn($a, $b) { $a + $b }
)
Result:
15

(This returns the sum of the items in the sequence).

Expression:
fold-right(
  1 to 5,
  "",
  concat(?, ".", ?)
)
Result:
"1.2.3.4.5."
Expression:
fold-right(
  1 to 5,
  "$z",
  concat("$f(", ?, ", ", ?, ")")
)
Result:
"$f(1, $f(2, $f(3, $f(4, $f(5, $z)))))"

17.2.15 fn:scan-left

Changes in 4.0  

  1. New in 4.0  [Issue 982 PR 1296 23 June 2024]

Summary

Produces the sequence of successive partial results from the evaluation of fn:fold-left with the same arguments.

Signature
fn:scan-left(
$inputas item()*,
$accuminitas item()*,
$actionas fn(item()*, item()) as item()*
) as array(*)*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

The function returns a sequence of N+1 single-member arraysDM, where N is the number of items in $input. For values of $n in the range 0 to N, the value of the single member of array $n+1 in the result sequence is the value of the expression fold-left( subsequence($input, 1, $n), $accuminit, $action ).

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

(0 to count($input)) 
  ! [fold-left( subsequence($input, 1, .), $accum, $action )]
(0 to count($input)) 
  ! [fold-left( subsequence($input, 1, .), $init, $action )]
Notes

A practical implementation is likely to compute each array in the result sequence based on the value of the previous item, rather than computing each item independently as implied by the specification.

Examples
Expression:
scan-left(1 to 5, 0, op('+'))
Result:
[ 0 ], [ 1 ], [ 3 ], [ 6 ], [ 10 ], [ 15 ]
Expression:
scan-left(1 to 3, 0, op('-'))
Result:
[ 0 ], [ -1 ], [ -3 ], [ -6 ]
Expression:
scan-left(1 to 5, 1, op('*'))
Result:
[ 1 ], [ 1 ], [ 2 ], [ 6 ], [ 24 ], [ 120 ]
Expression:
scan-left(1 to 3, (), fn($a, $b) { $b, $a })
Result:
[ () ], [ 1 ], [ (2, 1) ], [ (3, 2, 1) ] ]

17.2.16 fn:scan-right

Changes in 4.0  

  1. New in 4.0

Summary

Produces the sequence of successive partial results from the evaluation of fn:fold-right with the same arguments.

Signature
fn:scan-right(
$inputas item()*,
$accuminitas item()*,
$actionas fn(item()*, item()) as item()*
) as array(*)*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

The function returns a sequence of N+1 single-member arraysDM, where N is the number of items in $input. For values of $n in the range 0 to N, the value of the single member of array $n+1 in the result sequence is the value of the expression fold-right( subsequence($input, count($input)-$n+1), $accuminit, $action ).

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

(0 to count($input)) 
  ! [fold-right( subsequence($input, count($input)-.+1), $accum, $action )]
(0 to count($input)) 
  ! [fold-right( subsequence($input, count($input)-.+1), $init, $action )]
Notes

A practical implementation is likely to compute each array in the result sequence based on the value of the previous item, rather than computing each item independently as implied by the specification.

Examples
Expression:
scan-right(1 to 10, 0, op('+'))
Result:
[ 55 ], [ 54 ], [ 52 ], [ 49 ], [ 45 ],
[ 40 ], [ 34 ], [ 27 ], [ 19 ], [ 10 ], [ 0 ]
Expression:
scan-right(1 to 3, 0, op('-'))
Result:
[ 2 ], [ -1 ], [ 3 ], [ 0 ]
Expression:
scan-right(1 to 5, (), fn($a, $b) { $b, $a })
Result:
[(5,4,3,2,1)], [(5,4,3,2)], [(5,4,3)], [(5,4)], [5], [()]

19 Processing arrays

Arrays were introduced as a new datatype in XDM 3.1. This section describes functions that operate on arrays.

An array is an additional kind of item. An array of size N is a mapping from the integers (1 to N) to a set of values, called the members of the array, each of which is an arbitrary sequence. Because an array is an item, and therefore a sequence, arrays can be nested.

An array acts as a function from integer positions to associated values, so the function call $array($index) can be used to retrieve the array member at a given position. The function corresponding to the array has the signature function($index as xs:integer) as item()*. The fact that an array is a function item allows it to be passed as an argument to higher-order functions that expect a function item as one of their arguments.

19.2 Functions that Operate on Arrays

The functions defined in this section use a conventional namespace prefix array, which is assumed to be bound to the namespace URI http://www.w3.org/2005/xpath-functions/array.

As with all other values, arrays are treated as immutable. For example, the array:reverse function returns an array that differs from the supplied array in the order of its members, but the supplied array is not changed by the operation. Two calls on array:reverse with the same argument will return arrays that are indistinguishable from each other; there is no way of asking whether these are “the same array”. Like sequences, arrays have no identity.

All functionality on arrays is defined in terms of two primitives:

  • The function array:members decomposes an array to a sequence of value records.

  • The function array:of-members composes an array from a sequence of value records.

A value record here is an item that encapsulates an arbitrary value; the representation chosen for a value record is record(value as item()*), that is, a map containing a single entry whose key is the string "value" and whose value is the encapsulated sequence.

FunctionMeaning
array:appendReturns an array containing all the members of a supplied array, plus one additional member at the end.
array:buildReturns an array obtained by evaluating the supplied function once for each item in the input sequence.
array:emptyReturns true if the supplied array contains no members.
array:filterReturns an array containing those members of the $array for which $predicate returns true. A return value of () is treated as false.
array:flattenReplaces any array appearing in a supplied sequence with the members of the array, recursively.
array:fold-leftEvaluates the supplied function cumulatively on successive members of the supplied array.
array:fold-rightEvaluates the supplied function cumulatively on successive values of the supplied array.
array:footReturns the last member of an array.
array:for-eachReturns an array whose size is the same as array:size($array), in which each member is computed by applying $action to the corresponding member of $array.
array:for-each-pairReturns an array obtained by evaluating the supplied function once for each pair of members at the same position in the two supplied arrays.
array:getReturns the value at the specified position in the supplied array (counting from 1).
array:headReturns the first member of an array, that is $array(1).
array:index-ofReturns a sequence of positive integers giving the positions within the array $array of members that are equal to $target.
array:index-whereReturns the positions in an input array of members that match a supplied predicate.
array:insert-beforeReturns an array containing all the members of the supplied array, with one additional member at a specified position.
array:itemsReturns the sequence concatenation of the members of an array.
array:joinConcatenates the contents of several arrays into a single array, with an optional separator between adjacent members.
array:membersDelivers the contents of an array as a sequence of value records.
array:of-membersConstructs an array from the contents of a sequence of value records.
array:putReturns an array containing all the members of a supplied array, except for one member which is replaced with a new value.
array:removeReturns an array containing all the members of the supplied array, except for the members at specified positions.
array:reverseReturns an array containing all the members of a supplied array, but in reverse order.
array:sizeReturns the number of members in the supplied array.
array:sliceReturns an array containing selected members of a supplied input array based on their position.
array:sortSorts a supplied array, based on the value of a number of sort keys supplied as functions.
array:splitDelivers the contents of an array as a sequence of single-member arrays.
array:subarrayReturns an array containing all members from a supplied array starting at a supplied position, up to a specified length.
array:tailReturns an array containing all members except the first from a supplied array.
array:trunkReturns an array containing all members except the last from a supplied array.

19.2.6 array:fold-left

Summary

Evaluates the supplied function cumulatively on successive members of the supplied array.

Signature
array:fold-left(
$arrayas array(*),
$accuminitas item()*,
$actionas fn(item()*, item()*) as item()*
) as item()*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

The function is defined formally below, in terms of the equivalent fn:fold-left function for sequences.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

fold-left(
  array:members($array),
  $accum,
  fn($result, $member) { $action($result, map:get($member, 'value')) }
)
fold-left(
  array:members($array),
  $init,
  fn($result, $member) { $action($result, map:get($member, 'value')) }
)
Notes

If the supplied array is empty, the function returns $accuminit.

If the supplied array contains a single member $m, the function returns $accuminit => $action($m).

If the supplied array contains two members $m and $n, the function returns $accuminit => $action($m) => $action($n); and similarly for an input array with more than two members.

Examples
ExpressionResult
array:fold-left(
  [ true(), true(), false() ],
  true(),
  fn($x, $y) { $x and $y }
)
false()

(Returns true if every member of the input array has an effective boolean value of true().)

array:fold-left(
  [ true(), true(), false() ],
  false(), 
  fn($x, $y) { $x or $y }
)
true()

(Returns true if at least one member of the input array has an effective boolean value of true().)

array:fold-left(
  [ 1, 2, 3 ],
  [],
  fn($x, $y) { [ $x, $y ] }
)
[[[[], 1], 2], 3]

19.2.7 array:fold-right

Changes in 4.0  

  1. The $action callback function now accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Evaluates the supplied function cumulatively on successive values of the supplied array.

Signature
array:fold-right(
$arrayas array(*),
$accuminitas item()*,
$actionas fn(item()*, item()*) as item()*
) as item()*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

The function is defined formally below, in terms of the equivalent fn:fold-right function for sequences.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

fold-right(
  array:members($array),
  $accum,
  fn($member, $result) { $action(map:get($member, 'value'), $result) }
)
fold-right(
  array:members($array),
  $init,
  fn($member, $result) { $action(map:get($member, 'value'), $result) }
)
Notes

If the supplied array is empty, the function returns $accuminit.

If the supplied array contains a single member $m, the function returns $action($m, $accuminit).

If the supplied array contains two members $m and $n, the function returns $action($m, $action($n, $accuminit)); and similarly for an input array with more than two members.

Examples
ExpressionResult
array:fold-right(
  [ true(), true(), false() ],
  true(),
  fn($x, $y) { $x and $y }
)
false()

(Returns true if every member of the input array has an effective boolean value of true().)

array:fold-right(
  [ true(), true(), false() ],
  false(),
  fn($x, $y) { $x or $y }
)
true()

(Returns true if at least one member of the input array has an effective boolean value of true().)

array:fold-right(
  [ 1, 2, 3 ],
  [],
  fn($x, $y) { [ $x, $y ] }
)
[ 1, [ 2, [ 3, [] ] ] ]