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 2 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/>

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) 4.0]. It also defines functions and operators on nodes and node sequences as defined in the [XQuery and XPath Data Model (XDM) 4.0]. 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 H Changes since 3.1.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document.

This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft is work in progress and should not be considered either stable or complete. Standard W3C copyright and patent conditions apply.

The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.

As the Community Group moves towards publishing dated, stable drafts, some features that the group thinks may likely be removed or substantially changed are marked “at risk” in their changes section. In this draft:

The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test respectively. New tests, or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata describing the conditions for applicability of each test case as well as the expected results. They do not include any test drivers for executing the tests: each implementation is expected to provide its own test driver.

Dedication

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


1 Introduction

Changes in 4.0 (next)

  1. If a section of this specification has been updated since version 3.1, an overview of the changes is provided, along with links to navigate to the next or previous change.

  2. Sections with significant changes are marked with a ✭ symbol in the table of contents. New functions are indicated by ✚.

The purpose of this document is to define functions and operators for inclusion in XPath 4.0, XQuery 4.0, and XSLT 4.0. The exact syntax used to call these functions and operators is specified in [XML Path Language (XPath) 4.0], [XQuery 4.0: An XML Query Language] and [XSL Transformations (XSLT) Version 4.0].

This document defines three classes of functions:

[XML Schema Part 2: Datatypes Second Edition] defines a number of primitive and derived datatypes, collectively known as built-in datatypes. This document defines functions and operations on these datatypes as well as the other types (for example, nodes and sequences of nodes) defined in 2.7 Schema Information DM31 of the [XQuery and XPath Data Model (XDM) 4.0]. These functions and operations are available for use in [XML Path Language (XPath) 4.0], [XQuery 4.0: An XML Query Language] and any other host language that chooses to reference them. In particular, they may be referenced in future versions of XSLT and related XML standards.

[XSD 1.1 Part 2] adds to the datatypes defined in [XML Schema Part 2: Datatypes Second Edition]. It introduces a new derived type xs:dateTimeStamp, and it incorporates as built-in types the two types xs:yearMonthDuration and xs:dayTimeDuration which were previously XDM additions to the type system. In addition, XSD 1.1 clarifies and updates many aspects of the definitions of the existing datatypes: for example, it extends the value space of xs:double to allow both positive and negative zero, and extends the lexical space to allow +INF; it modifies the value space of xs:Name to permit additional Unicode characters; it allows year zero and disallows leap seconds in xs:dateTime values; and it allows any character string to appear as the value of an xs:anyURI item. Implementations of this specification may support either XSD 1.0 or XSD 1.1 or both.

In some cases, this specification references XSD for the semantics of operations such as the effect of matching using regular expressions, or conversion of atomic items to strings. In most such cases there is no intended technical difference between the XSD 1.0 and XSD 1.1 specifications, but the 1.1 version often provides clearer explanations and sometimes also corrects technical errors. In such cases this specification often chooses to reference the XSD 1.1 specification. This should not be taken as implying that it is necessary to invoke an XSD 1.1 processor.

References to specific sections of some of the above documents are indicated by cross-document links in this document. Each such link consists of a pointer to a specific section followed a superscript specifying the linked document. The superscripts have the following meanings: XQ [XQuery 4.0: An XML Query Language], XT [XSL Transformations (XSLT) Version 4.0], XP [XML Path Language (XPath) 4.0], and DM [XQuery and XPath Data Model (XDM) 4.0].

1.3 Namespaces and prefixes

The functions and operators defined in this document are contained in one of several namespaces (see [Namespaces in XML]) and referenced using an xs:QName.

This document uses conventional prefixes to refer to these namespaces. User-written applications can choose a different prefix to refer to the namespace, so long as it is bound to the correct URI. The host language may also define a default namespace for function calls, in which case function names in that namespace need not be prefixed at all. In many cases the default namespace will be http://www.w3.org/2005/xpath-functions, allowing a call on the fn:name function (for example) to be written as name() rather than fn:name(); in this document, however, all example function calls are explicitly prefixed.

The URIs of the namespaces and the conventional prefixes associated with them are:

  • http://www.w3.org/2001/XMLSchema for constructors — associated with xs.

    The section 2223 Constructor functions defines constructor functions for the built-in datatypes defined in [XML Schema Part 2: Datatypes Second Edition] and in 2.7 Schema Information DM31 of [XQuery and XPath Data Model (XDM) 4.0]. These datatypes and the corresponding constructor functions are in the XML Schema namespace, http://www.w3.org/2001/XMLSchema, and are named in this document using the xs prefix.

  • http://www.w3.org/2005/xpath-functions for functions — associated with fn.

    The namespace prefix used in this document for most functions that are available to users is fn.

  • http://www.w3.org/2005/xpath-functions/math for functions — associated with math.

    This namespace is used for some mathematical functions. The namespace prefix used in this document for these functions is math. These functions are available to users in exactly the same way as those in the fn namespace.

  • http://www.w3.org/2005/xpath-functions/map for functions — associated with map.

    This namespace is used for some functions that manipulate maps (see 14.4 Functions that operate on maps). The namespace prefix used in this document for these functions is map. These functions are available to users in exactly the same way as those in the fn namespace.

  • http://www.w3.org/2005/xpath-functions/array for functions — associated with array.

    This namespace is used for some functions that manipulate maps (see 15.2 Functions that operate on arrays). The namespace prefix used in this document for these functions is array. These functions are available to users in exactly the same way as those in the fn namespace.

  • http://www.w3.org/2005/xpath-functions/generators for functions — associated with generators.

    This namespace is used for some functions that manipulate generators (see 18.4 Functions on generators). The namespace prefix used in this document for these functions is gn. These functions are available to users in exactly the same way as those in the fn namespace.

  • http://www.w3.org/2005/xqt-errors — associated with err.

    There are no functions in this namespace; it is used for error codes.

    This document uses the prefix err to represent the namespace URI http://www.w3.org/2005/xqt-errors, which is the namespace for all XPath and XQuery error codes and messages. This namespace prefix is not predeclared and its use in this document is not normative.

  • http://www.w3.org/2010/xslt-xquery-serialization — associated with output.

    There are no functions in this namespace: it is used for serialization parameters, as described in [XSLT and XQuery Serialization 3.1]

  • Functions defined with the op prefix are described here to underpin the definitions of the operators in [XML Path Language (XPath) 4.0], [XQuery 4.0: An XML Query Language] and [XSL Transformations (XSLT) Version 4.0]. These functions are not available directly to users, and there is no requirement that implementations should actually provide these functions. For this reason, no namespace is associated with the op prefix. For example, multiplication is generally associated with the * operator, but it is described as a function in this document:

    op:numeric-multiply(
    $arg1as xs:numeric,
    $arg2as xs:numeric
    ) as xs:numeric

    Sometimes there is a need to use an operator as a function. To meet this requirement, the function fn:op takes any simple binary operator as its argument, and returns a corresponding function. So for example fn:for-each-pair($seq1, $seq2, op("+")) performs a pairwise addition of the values in two input sequences.

Note:

The above namespace URIs are not expected to change from one version of this document to another. The contents of these namespaces may be extended to allow additional functions (and errors, and serialization parameters) to be defined.

4 Processing numerics

This section specifies arithmetic operators on the numeric datatypes defined in [XML Schema Part 2: Datatypes Second Edition].

4.1 Numeric types

The operators described in this section are defined on the following atomic types.

    • decimal

      • integer

    • double

    • float

Legend:

  • Supertype

    • subtype

  • Built-in atomic types

They also apply to types derived by restriction from the above types.

The type xs:numeric is defined as a union type whose member types are (in order) xs:double, xs:float, and xs:decimal. This type is implicitly imported into the static context, so it can also be used in defining the signature of user-written functions. Apart from the fact that it is implicitly imported, it behaves exactly like a user-defined type with the same definition. This means, for example:

  • If the expected type of a function parameter is given as xs:numeric, the actual value supplied can be an instance of any of these three types, or any type derived from these three by restriction (this includes the built-in type xs:integer, which is derived from xs:decimal).

  • If the expected type of a function parameter is given as xs:numeric, and the actual value supplied is xs:untypedAtomic (or a node whose atomized value is xs:untypedAtomic), then it will be cast to the union type xs:numeric using the rules in 23.3.724.3.7 Casting to union types. Because the lexical space of xs:double subsumes the lexical space of the other member types, and xs:double is listed first, the effect is that if the untyped atomic item is in the lexical space of xs:double, it will be converted to an xs:double, and if not, a dynamic error occurs.

  • When the return type of a function is given as xs:numeric, the actual value returned will be an instance of one of the three member types (and perhaps also of types derived from these by restriction). The rules for the particular function will specify how the type of the result depends on the values supplied as arguments. In many cases, for the functions in this specification, the result is defined to be the same type as the first argument.

Note:

This specification uses [IEEE 754-2019] arithmetic for xs:float and xs:double values. One consequence of this is that some operations result in the value NaN (not a number), which has the unusual property that it is not equal to itself. Another consequence is that some operations return the value negative zero. This differs from [XML Schema Part 2: Datatypes Second Edition], which defines NaN as being equal to itself and defines only a single zero in the value space. The text accompanying several functions defines behavior for both positive and negative zero inputs and outputs in the interest of alignment with [IEEE 754-2019]. A conformant implementation must respect these semantics. In consequence, the expression -0.0e0 (which is actually a unary minus operator applied to an xs:double value) will always return negative zero: see 4.2.8 op:numeric-unary-minus. As a concession to implementations that rely on implementations of XSD 1.0, however, when casting from string to double the lexical form -0may be converted to positive zero, though negative zero is recommended.

XML Schema 1.1 introduces support for positive and negative zero as distinct values, and also uses the [IEEE 754-2019] semantics for comparisons involving NaN.

4.5 Parsing numbers

It is possible to convert strings to values of type xs:integer, xs:float, xs:decimal, or xs:double using the constructor functions described in 2223 Constructor functions or using cast expressions as described in 2324 Casting.

In addition the fn:number function is available to convert strings to values of type xs:double. It differs from the xs:double constructor function in that any value outside the lexical space of the xs:double datatype is converted to the xs:double value NaN.

FunctionMeaning
fn:numberReturns the value indicated by $value or, if $value is not specified, the context value after atomization, converted to an xs:double.
fn:parse-integerConverts a string to an integer, recognizing any radix in the range 2 to 36.

4.5.1 fn:number

Summary

Returns the value indicated by $value or, if $value is not specified, the context value after atomization, converted to an xs:double.

Signature
fn:number(
$valueas xs:anyAtomicType?:= .
) as xs:double
Properties

The zero-argument form of this function is deterministic, context-dependent, and focus-dependent.

The one-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

Calling the zero-argument version of the function is defined to give the same result as calling the single-argument version with the context value (.). That is, fn:number() is equivalent to fn:number(.), as defined by the rules that follow.

If $value is the empty sequence or if $value cannot be converted to an xs:double, the xs:double value NaN is returned.

Otherwise, $value is converted to an xs:double following the rules of 23.1.3.224.1.3.2 Casting to xs:double. If the conversion to xs:double fails, the xs:double value NaN is returned.

Error Conditions

A type error is raised [err:XPDY0002]XP if $value is omitted and the context value is absentDM.

As a consequence of the rules given above, a type error is raised [err:XPTY0004]XP if the context value cannot be atomized, or if the result of atomizing the context value is a sequence containing more than one atomic item.

Notes

XSD 1.1 allows the string +INF as a representation of positive infinity; XSD 1.0 does not. It is implementation-defined whether XSD 1.1 is supported.

Generally fn:number returns NaN rather than raising a dynamic error if the argument cannot be converted to xs:double. However, a type error is raised in the usual way if the supplied argument cannot be atomized or if the result of atomization does not match the required argument type.

Examples
Variables
let $e := <e price="12.1" discount="NONE"/>
ExpressionResult
number(12)

1.2e1

number('12')

1.2e1

number('INF')

xs:double('INF')

number('NaN')

xs:double('NaN')

number('non-numeric')

xs:double('NaN')

number($e/@price)

1.21e1

number($e/@discount)

xs:double('NaN')

number($e/@misspelt)

xs:double('NaN')

("10", "11", "12") ! number()

1.0e1, 1.1e1, 1.2e1

12 Processing nodes

12.1 Accessors

Accessors and their semantics are described in [XQuery and XPath Data Model (XDM) 4.0]. Some of these accessors are exposed to the user through the functions described below.

Each of these functions has an arity-zero signature which is equivalent to the arity-one form, with the context value supplied as the implicit first argument. In addition, each of the arity-one functions accepts an empty sequence as the argument, in which case it generally delivers an empty sequence as the result: the exception is fn:string, which delivers a zero-length string.

FunctionAccessorAcceptsReturns
fn:node-namenode-namenode (optional)xs:QName (optional)
fn:nillednillednode (optional)xs:boolean (optional)
fn:stringstring-valueitem (optional)xs:string
fn:datatyped-valuezero or more itemsa sequence of atomic items
fn:base-uribase-urinode (optional)xs:anyURI (optional)
fn:document-uridocument-urinode (optional)xs:anyURI (optional)
FunctionMeaning
fn:base-uriReturns the base URI of a node.
fn:document-uriReturns the URI of a resource where a document can be found, if available.
fn:nilledReturns true for an element that is nilled.
fn:node-nameReturns the name of a node, as an xs:QName.
fn:stringReturns the value of $value represented as an xs:string.
fn:dataReturns the result of atomizing a sequence. This process flattens arrays, and replaces nodes by their typed values.

12.1.5 fn:string

Summary

Returns the value of $value represented as an xs:string.

Signature
fn:string(
$valueas item()?:= .
) as xs:string
Properties

The zero-argument form of this function is deterministic, context-dependent, and focus-dependent.

The one-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

In the zero-argument version of the function, $value defaults to the context value. That is, calling fn:string() is equivalent to calling fn:string(.).

If $value is the empty sequence, the function returns the zero-length string.

If $value is an XNodeDM, the function returns the string value of the node, as obtained using the dm:string-value accessor defined in [XQuery and XPath Data Model (XDM) 3.1] (see [XQuery and XPath Data Model (XDM) 4.0] section 7.6.12 string-value Accessor).

If $value is a JNodeDM, the function returns the result of string(jnode-content($value)). This will fail in the case where jnode-content($value) is a map or an array.

If $value is an atomic item, the function returns the result of the expression $value cast as xs:string (see 2324 Casting).

In all other cases, a dynamic error occurs (see below).

Error Conditions

The following errors may be raised when $value is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP.

  • If the context value is not an instance of the sequence type item()?, type error [err:XPTY0004]XP.

A type error is raised [err:FOTY0014] if $value is a function item (this includes maps and arrays).

Notes

Every node has a string value, even an element with element-only content (which has no typed value). Moreover, casting an atomic item to a string always succeeds. Functions, maps, and arrays have no string value, so these satisfy the type signature but cause failure. Applying the string function to a JNode succeeds if the JNode wraps a simple value such as a string, number, or boolean, or if it wraps an XNode, but it fails in the case where the JNode wraps a map or an array.

Examples
Variables
let $para := <para>There lived a <term author="Tolkien">hobbit</term>.</para>
ExpressionResult
string(23)

"23"

string(false())

"false"

string("Paris")

"Paris"

string((1, 2, 3))

Raises error XPTY0004.

string([ [ 1, 2 ], [ 3, 4 ] ])

Raises error FOTY0014.

string(abs#1)

Raises error FOTY0014.

string({"x": [10, 20, 30]} / x / *[3])

"30"

string($para)

"There lived a hobbit."

18 Deferred evaluation

Deferred-evaluation is achieved in a user-controlled way, using the system-defined fn:generator record.

Deferred-evaluation is particularly useful when solving any problem, where data sources of unknown or unpredictable size must be handled, and only one or a few values from these are needed at any time during the processing.

18.1 Major use-cases

The f:generator record is a tool for solutions needed for the following use-cases:

  1. Processing a huge data-source whose values may not all be needed. A generator produces only the next value from the data-source and only on demand basis.

  2. Handling a data-source providing unknown or infinite number of values. When requested for the next value of the data-source the generator always produces it, if the data-source still contains any values. It is the responsibility of the caller to issue only the necessary number of requests for the really needed next values.

What is achieved in these two cases:

  • A (next) value is produced only on request. No time is spent on producing all values of the collection.

  • A (next) value is produced only on request. No memory is consumed to store all values of the collection.

18.2 Definitions

The following terms are defined:

  • [Definition] An XPath collection or just collection has nothing to do with the f:collection function. An XPath collection can be a sequence, an array or a map.

  • [Definition] Generator value - a "value" produced by a call to the generator method get-current can be either an individual XPath item() or an XPath sequence.

  • [Definition] Generator instance - a given instance of the f:generator record or the result produced by a chain of one or more applications of the move-next method starting from a given f:generator instance.

  • [Definition] The term the next value of a generator denotes the value returned from the get-current() method applied on the generator-instance produced by the move-next() method, if the end-reached field of this next generator-instance is false(). This is also the next value in the generator's yield - see below.

  • [Definition] The term yield (of a generator) denotes the consecutive values returned from calling the move-next() and then the get-current method starting from the current generator instance, and on each generator instance thus produced, by applying the move-next() method and then the get-current method until move-next() produces a generator instance whose end-reached field is true().

    Note:

    1. Thus, if the consecutive generator instances produced by continuously applying the move-next() method on each of them, starting from the initialized $G1 generator is:

      $G2, $G3, ... , $Gn, ..., then the yield of the generator $G1 is exactly these consecutive generator values:

      $G1 =?> get-current(), $G2 =?> get-current(), ..., $Gn =?> get-current(), ...

    2. If the sequence of the generator instances thus produced is finite (for the final produced generator $Gm, $Gm?end-reached eq true(), then the yield is:

      $G1 =?> get-current(), $G2 =?> get-current(), ..., $Gm-1 =?> get-current()

    3. If the $G1 generator is not initialized ($G1?initialized eq false()), then the yield of this generator is the same as the yield of the (first initialized in the chain) $G2 generator:

      $G2 =?> get-current(), $G3 =?> get-current(), ..., $Gn =?> get-current(), ...

    4. The yield is empty, if $G1?end-reached eq true and the yield is infinite if neither $G1?end-reached eq true() nor any of the consecutive applications of move-next produces a generator $Gx, such that $Gx?end-reached eq true().

  • [Definition] A generator is empty if and only if its field end-reached has the effective boolean value true(). An empty generator-instance reached in the chain produced by successive evaluations of the move-next method signifies that the yield of a starting generator-instance has been fully traversed. It has the following properties:
    1. get-current's evaluation raises an error.

    2. move-next's evaluation raises an error.

    Note:

    Empty generators may arise in two ways:

    1. Produced by the function gn:empty-generator.

    2. Termination of a chain of generator instances - the final value of repeated application of the move-next method is an empty generator instance.

      Generators with infinite yield never reach an empty-generator instance in this process.

The fields of the f:generator record, including its methods are defined in the next sections.

18.3 Record fn:generator

This record type is used as a tool for implementing deferred evaluation upon collections of values. The user has to maintain the four record fields, provided below. The generator type is extensible thus the user can add any additional fields as appropriate. Fields of fn:generator :

NameMeaning

initialized

If the value of initialized is false() calling $generator =?> get-current() raises error [err:FOGR0001]. When a $generator is initially created, sometimes it makes sense to perform additional, initializing actions on it, before it becomes possible to extract its current value. In such case, in order to get the first value of the yield, the caller must call $generator =?> move-next() and the move-next method should produce a new generator, whose initialized field is true()

  • Type: xs:boolean

end-reached

Indicates whether or not the yield of the generator is empty. If after a call to move-next() the value of the returned generator's end-reached field is true() then further calling move-next() or get-current() on this generator raises error [err:FOGR0002].

  • Type: xs:boolean

get-current

This function produces the current value of the generator after the last call to move-next(), if this last call didn't return a generator whose end-reached value was true(). get-current() must only be called if the value of initialized is true() and the value of end-reached is false(), otherwise an error, respectively [err:FOGR0001] or [err:FOGR0002], is raised.

  • Type: fn($this as f:generator) as item()*

move-next

This function, when called on a generator-instance whose end-reached value is false(), produces the next generator-instance, whose end-reached field could be true(), however if after the call this field of the produced generator-instance is still false(), then calling get-current()) on this resulting generator-instance produces the "next value" of the generator.

  • Type: fn($this as f:generator) as f:generator

*

The record type is extensible (it may contain additional fields beyond those listed).

18.4 Functions on generators

The functions defined in this section use a conventional namespace prefix "gn", which is assumed to be bound to the namespace URI http://www.w3.org/2005/xpath-functions/generator. They are listed under the following categories, based on the type of the function result:

  • Functions returning a specific value: an item() or a sequence.

  • Functions that produce another generator from existing generators.

  • Functions that produce a generator from data by a data-provider.

  • Functions that produce an XPath collection from the yield of a generator.

These functions do not evaluate eagerly the yield of any of their generator-operands. A value from a yield is produced only if explicitly requested by evaluating the methods move-next and get-current. At no point in the computation it is necessary to have all values of a yield available. In most cases a function would only need one or a few values from a yield. No unnecessary computation of a value from a yield is done and no memory is used to hold such unnecessary value at any point in the computation. This is why the evaluation of the functions defined here is referred to as "Deferred Evaluation".

Note:

Most of the examples in this section depend on the definition of the following variables:

$gen2ToInf := f:generator(initialized := true(), end-reached := false(), 
                              get-current := fn($this as f:generator){$this?last +1},
                              move-next := fn($this as f:generator)
                              {
                                if(not($this?initialized))
                                  then map:put($this, "initialized", true())
                                  else map:put($this, "last", $this?last + 1)
                              }
                             ) => map:put("last", 1),
    $genN := $gen2ToInf => map:put("last", 0),
    $gen0toInf := $gen2ToInf => map:put("last", -1),
    $double := fn($n) {2*$n},
    $sum2 := fn($m, $n) {$m + $n},
    $product := fn($m, $n) {$m * $n},
    $factorial := fn($n) {fold-left(1 to $n, 1, $product)}

The examples use three generators with infinite yields:

  • $gen2ToInf with yield - all integers in the interval from 2 to Infinity ([2, ∞])

  • $genN with yield - the sequence of all natural numbers: all integers in [1, ∞]

  • $gen0toInf with yield - the sequence of all non-negative numbers: all integers in [0, ∞]

And four functions:

  • $double returns its argument, multiplied by 2.

  • $sum2 returns the sum of its two arguments.

  • $product returns the product of its two arguments.

  • $factorial given a non-negative argument $n returns its factorial ($n)!.

18.4.1 Functions returning a specific value

This group of functions returns a single value computed from the yield of a supplied generator. Each function inspects the yield only as far as necessary to obtain that value.

FunctionMeaning
gn:at Returns the $k-th value from the yield of the $generator
gn:contains Returns true() if the $value is contained in the yield of the generator, and false() otherwise. The comparisons are done using fn:deep-equal.
gn:first-where Returns the first $value in the yield of the generator for which $predicate($value) is true(). If the generator's yield doesn't contain any such item, error [err:FOGR0002] is raised.
gn:fold-leftProcesses consecutively the values of the yield of the supplied generator, applying the supplied function repeatedly to each value in turn, together with an accumulated result value.
gn:fold-rightProcesses consecutively from right to left the values of the yield of the supplied generator, applying the supplied function repeatedly to each value in turn, together with an accumulated result value.
gn:fold-lazyProduces the same result as gn:fold-right on the entire yield of the $generator with the operation specified by $action but also performs short-circuiting if detected by the supplied $short-circuit-detector function.
gn:headProduces the first value contained in the yield of the $generator.
gn:someReturns true() if and only if the generator is initialized and its yield contains at least one value.
gn:some-whereReturns true() if the generator is initialized and its yield contains any value upon which evaluating the supplied predicate returns true(). Otherwise, false() is returned.
gn:valueProduces the value contained in this generator-instance.
18.4.1.1 gn:at
Summary

Returns the $k-th value from the yield of the $generator

Signature
gn:at(
$generatoras fn:generator,
$kas xs:positiveInteger
) as item()*
Properties

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

Rules

If $k is greater than the number of items contained in the generator's yield, error [err:FOGR0002] is raised.

Formal Equivalent

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

gn:subrange($generator, $k, $k) =?> get-current()
Examples
ExpressionResult
$gen2ToInf => gn:at(1)

2

$gen2ToInf => gn:at(5)

6

$gen2ToInf => take(5) => gn:at(6)

Raises error FOGR0002.

18.4.1.2 gn:contains
Summary

Returns true() if the $value is contained in the yield of the generator, and false() otherwise. The comparisons are done using fn:deep-equal.

Signature
gn:contains(
$generatoras fn:generator,
$valueas item()*
) as xs:boolean
Properties

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

Rules

The comparisons are done using fn:deep-equal.

Formal Equivalent

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

let $gen := if(not($gen?initialized)) then  $gen =?> move-next()
              else $gen
 return
  if($gen?end-reached) then false()
   else
     let $current := $gen =?> get-current()
       return
          if(deep-equal($current, $value)) then true()
            else gn:contains($gen =?> move-next(), $value)
Examples
ExpressionResult
$genN => gn:take(10) => gn:contains(3)

true()

$genN => gn:take(10) => gn:contains(20)

false()

$genN => gn:take(10) => gn:contains(0)

false()

$genN => gn:take(10) => gn:contains(11)

false()

$genN => gn:contains(15)

true()

18.4.1.3 gn:first-where
Summary

Returns the first $value in the yield of the generator for which $predicate($value) is true(). If the generator's yield doesn't contain any such item, error [err:FOGR0002] is raised.

Signature
gn:first-where(
$generatoras fn:generator,
$predicateas fn(item()*) as xs:boolean
) as item()*
Properties

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

Rules

The $predicate function is applied consecutively on every value in the yield of the $generator until it returns true(). This value is then returned as the result.

Formal Equivalent

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

$gen => gn:skip-while(fn($x as item()*){not($pred($x))}) => gn:head()
Examples
ExpressionResult
$gen2ToInf => gn:first-where(fn($n){$n gt 10})

11

$gen2ToInf => gn:chunk(10)  
           =>  gn:first-where(
                    fn($arr as array(*))
                    {$arr(1) le 33 and $arr(10) ge 33})

[32,33,34,35,36,37,38,39,40,41]

18.4.1.4 gn:fold-left
Summary

Processes consecutively the values of the yield of the supplied generator, applying the supplied function repeatedly to each value in turn, together with an accumulated result value.

Signature
gn:fold-left(
$generatoras fn:generator,
$initas item()*,
$actionas fn(item()*, item()*) as item()*) as item()*
) as item()*
Properties

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

Rules

Let the yield of the $generator contains N values. Let us denote these N values as V1, V2, ..., VN.

If N eq 0 the function returns $init.

If N gt 0 the function calls $action($init, V1) returning a value A1.

If the yield of the $generator contains a second value, the function then calls $action(A1, V2) returning a value A2. To process the kth value it calls $action(Ak-1, Vk)

This continues in the same way until the end of the yield of the$generator; 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 gn:fold-left($generator, 
                              $init as item()*,  
                              $action as fn(item()*, item()*) as item()*) as item()*
{
  if($generator?end-reached) then $init
    else gn:fold-left(gn:tail($generator), 
                      $action($init, $gen =?> get-current()), 
                      $action)		
}
Examples
ExpressionResult
$gen2ToInf => gn:take(5) => gn:fold-left(0, fn($x, $y){$x + $y})

20

gn:empty-generator() 
    => gn:fold-left(54321, fn($x, $y){$x + $y})

54321

$gen0toInf 
    => gn:for-each(fn($n){(2 * $n + 1) 
                          div $factorial(2*xs:decimal($n)})
    => gn:take(8) 
    => gn:fold-left(0, fn($x, $y){$x + $y})

2.718281828458229747

18.4.1.5 gn:fold-right
Summary

Processes consecutively from right to left the values of the yield of the supplied generator, applying the supplied function repeatedly to each value in turn, together with an accumulated result value.

Signature
gn:fold-right(
$generatoras fn:generator,
$initas item()*,
$actionas fn(item()*, item()*) as item()*) as item()*
) as item()*
Properties

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

Rules

Let the yield of the $generator contains n values. Let us denote these n values as V1, V2, ..., Vn.

If n eq 0 the function returns $init.

If n gt 0 the function calls $action(Vn, $init) returning a value An-1.

If the yield of the $generator contains a previous value, the function then calls $action(Vn-1, An-1) returning a value An-2. To process the kth value it calls $action(Vk, Ak-1)

This continues in the same way until the starting value of the yield of the$generator is reached; the final result is the result of the last call on $action, that is A0.

Formal Equivalent

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

declare function gn:fold-right($generator, 
                              $init as item()*,  
                              $action as fn(item()*, item()*) as item()*) as item()*
{
  if($generator?end-reached) then $init
    else $action(gn:head($generator), 
	             gn:fold-right(gn:tail($generator), $init, $action))		
}
Examples
ExpressionResult
$gen2ToInf => gn:take(5) => gn:fold-right(0, fn($x, $y){$x + $y})

20

gn:empty-generator()
    => gn:fold-right(12345, fn($x, $y){$x + $y})

12345

18.4.1.6 gn:fold-lazy
Summary

Produces the same result as gn:fold-right on the entire yield of the $generator with the operation specified by $action but also performs short-circuiting if detected by the supplied $short-circuit-detector function.

Signature
gn:fold-lazy(
$generatoras fn:generator,
$initas item()*,
$actionas fn(item()*, item()*) as item()*) as item()*,
$short-circuit-detectoras fn(*) as item()*
) as item()*
Properties

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

Rules

If the yield of the $generator doesn't contain any value, $init is returned.

Otherwise, the same processing as done with gn:fold-right is performed, but on each step of the traversal of the yield of the $generator the function $short-circuit-detector is called, passing to it two arguments: the current value of the $generator's yield and the value of $init.

The result of applying $short-circuit-detector on these two arguments is a function. If the arity of the returned function is 0, this means that short-circuiting has been detected. In this case the folding process ends and the result of applying this 0-arity function is returned. For example, if $action is multiplication, a suitable $short-circuit-detector function returns fn() {0} if one of the two arguments passed to it is 0.

Note:

Detecting the possibility of a short-circuiting makes it possible to fold the contents of an infinite-yield generator - for example computing the product of the infinite sequence of integers in [-3, ∞].

Formal Equivalent

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

declare function gn:fold-lazy($generator as f:generator, 
                              $init as item()*, 
                              $action as fn(*), 
                              $short-circuit-detector as function(*)) as item()*
{
  if($generator?end-reached) then $init
  else
   let $current := $generator =?> get-current()
     return
       if(function-arity($short-circuit-detector($current, $init)) eq 0)
         then $short-circuit-detector($current, $init)()
         else $action($current, gn:fold-lazy($generator =?> move-next(), 
					     $init, 
					     $action, 
					     $short-circuit-detector))
}
Examples
ExpressionResult
let $multShortCircuitProvider := fn($x, $y)
        {
          if($x eq 0) then fn(){0}
            else fn($z) {$x * $z}
        },
        $gen-5ToInf := $gen2ToInf => gn:for-each(fn($n){$n -7})
     return
     (
       $gen2ToInf => gn:take(5) 
                  => gn:fold-lazy(1, $product, $multShortCircuitProvider),
				  
       $gen-5ToInf => gn:fold-lazy(1, $product, $multShortCircuitProvider)

(720, 0)

(An infinite product in the 2nd expression is successfully evaluated.)

18.4.1.7 gn:head
Summary

Produces the first value contained in the yield of the $generator.

Signature
gn:head(
$generatoras fn:generator
) as item()*
Properties

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

Rules

If the generator's yield doesn't contain any value, error [err:FOGR0002] is raised.

Formal Equivalent

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

gn:take($generator, 1) =?> get-current()
Examples
ExpressionResult
$gen2ToInf => gn:head()

2

$gen2ToInf => gn:tail() => gn:head()

3

gn:empty-generator() => gn:head()

Raises error FOGR0002.

18.4.1.8 gn:some
Summary

Returns true() if and only if the generator is initialized and its yield contains at least one value.

Signature
gn:some(
$generatoras fn:generator
) as xs:boolean
Properties

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

Rules

This function produces true() if the generator is initialized ($generator?initialized eq true()) and its yield contains values ($generator?end-reached eq false()).

Otherwise, the function returns false()

Formal Equivalent

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

$generator?initialized and not($generator?end-reached)
Examples
ExpressionResult
$gen2ToInf => gn:some()

true()

gn:empty-generator() => gn:some()

false()

18.4.1.9 gn:some-where
Summary

Returns true() if the generator is initialized and its yield contains any value upon which evaluating the supplied predicate returns true(). Otherwise, false() is returned.

Signature
gn:some-where(
$generatoras fn:generator,
$predicateas function(item()*) as xs:boolean
) as xs:boolean
Properties

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

Rules

This function produces true() if the generator is initialized ($generator?initialized eq true()) and when filtered with the given predicate, the yield of the produced generator contains values:

$generator => gn:filter($predicate) => gn:some() .

Otherwise, the function returns false()

Formal Equivalent

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

gn:some(gn:filter($generator, $predicate))
Examples
ExpressionResult
$gen2ToInf => gn:take(5) => gn:some-where(fn($n){$n ge 7})

false()

$gen2ToInf => gn:take(5) => gn:some-where(fn($n){$n ge 6})

true()

$gen2ToInf => gn:some-where(fn($n){$n ge 100})

true()

18.4.1.10 gn:value
Summary

Produces the value contained in this generator-instance.

Signature
gn:value(
$generatoras fn:generator
) as item()*
Properties

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

Rules

If the generator's yield doesn't contain any value, error [err:FOGR0002] is raised.

Otherwise returns the value obtained from the current generator-instance ($generator)

Note:

This function is a synonym for the generator method get-current. The goal is to free the end user from the nuisance of having to enter additional parentheses within an expression due to the different precedence of the =?> and => operators. Thus, instead of having to write:

($myGenerator => gn:take(5)) =?> get-current(), one simply writes:

$myGenerator => gn:take(5) => gn:value()

Formal Equivalent

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

$generator =?> get-current()
Examples
ExpressionResult
$gen2ToInf => gn:value()

2

$gen2ToInf => gn:take(3) => gn:skip(2) => gn:value(),

4

gn:empty-generator() => gn:value()

Raises error FOGR0002.

18.4.2 Functions that produce another generator from existing generators

Each of the functions in this section takes a generator as its first argument, and returns a generator. This allows chaining of function calls to produce complex transformations of the yields of the generators that are supplied as arguments. Only the starting instance of the result-generator is produced, and only the instances of the intermediate-result-generators that are required to compute this starting instance are produced.

FunctionMeaning
gn:appendCreates from a given $generator a new one whose yield is the yield of the original generator with the supplied $value appended to it.
gn:chunk Returns a new generator each of whose yield values is a "chunk" of consecutive values of the yield of the supplied $generator held in an array of size $size, with the possible exception that the size of the array containing the last "chunk" could be smaller.
gn:concat Returns a new generator whose yield consists of the yield of $generator followed by the yield of $generator2.
gn:distinctReturns a new generator whose yield contains only the distinct values from the original generator, in their original order.
gn:filterReturns a new generator whose yield contains exactly those values from the yield of the original generator, upon which the supplied predicate returns true(), in their original order.
gn:for-eachProduces a new generator, in the yield of which each value is the result of applying the function item $action on the corresponding value of the yield of the original $generator, in their original order.
gn:for-each-pairProduces a new generator, in the yield of which each value is the result of applying the function item $action on the corresponding values of the yields of $generator1 and $generator2, in their original order.
gn:insert-atReturns a generator whose yield contains the first $position - 1 values of the yield of $generator, followed by the supplied $value, followed by all the values of the yield of $generator starting from position $position.
gn:nextProduces the next state/generator-instance obtained from the current generator-instance $generator.
gn:prependReturns a generator, whose yield is the supplied $value followed by the values of the yield of the supplied $generator.
gn:remove-atReturns a generator, whose yield is the result of removing the $positionth value from the yield of the supplied $generator .
gn:remove-whereReturns a generator whose yield is the result of removing from the yield of the supplied $generator all values upon which the supplied $predicate is true().
gn:replaceReturns a generator, whose yield is the result of replacing in the yield of the supplied $generator the first value upon which the application of the supplied $predicate returns true() with the supplied $replacement .
gn:reverseReturns a generator, the values of whose yield are the ones in the yield of the supplied $generator but in reverse order.
gn:scan-leftReturns a generator whose yield contains the partial results of the evaluation of the gn:fold-left function with the same arguments.
gn:scan-rightReturns a generator whose yield contains the partial results of the evaluation of the gn:fold-right function with the same arguments.
gn:skipReturns a generator whose yield contains only the values of the yield of the supplied $generator after the $nth one and in their original order.
gn:skip-strictReturns a generator whose yield contains the values of the yield of the supplied $generator after the $nth one. If the yield of the supplied $generator contains less than $n values, and the supplied argument $raise-error-on-empty is true() then [err:FOGR0002] is raised.
gn:skip-whileReturns a new generator whose yield contains all the values from the yield of the supplied $generator, having removed the longest leading segment of values on which the supplied $predicate returns true().
gn:subrangeReturns a new generator whose yield contains the values from the yield of the original $generator, from position $start to position $endin their original order.
gn:tailReturns a new generator whose yield contains all the values but the first from the yield of the original $generator or raises [err:FOGR0002] if the supplied generator's yield is empty.
gn:takeReturns a new generator whose yield is the leading segment with length $n from the yield of the original $generator or raises [err:FOGR0002] if the supplied generator's yield is empty and $n is greater than 0.
gn:take-whileReturns a new generator whose yield contains the longest leading segment from the yield of the original $generator on all values of which the provided function $predicate returns true().
gn:zipReturns a new generator the kth value of whose yield is an array having two members: the kth value of the yield of $generator1 and the kth value of the yield of $generator2, where kdoes not exceed the smaller of the lengths of the yields of the two generators.
18.4.2.1 gn:append
Summary

Creates from a given $generator a new one whose yield is the yield of the original generator with the supplied $value appended to it.

Signature
gn:append(
$generatoras fn:generator,
$valueas item()*
) as fn:generator
Properties

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

Rules

A new generator Gen2 is created, whose yield has a single value: $value.

The function returns the result of applying gn:concat on the original $generator and the generator Gen2.

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
              else $generator,
    $genSingle := $gen => map:put("get-current", fn($this as f:generator){$value})
                       => map:put("move-next", fn($this as f:generator)
                                                 {gn:empty-generator()})
                       => map:put("end-reached", false())
 return
   gn:concat($gen, $genSingle)
Examples
ExpressionResult
$gen2ToInf => gn:append(101) instance of f:generator

true()

$gen2ToInf => gn:append(101) => gn:value()

2

$gen2ToInf => gn:take(5) => gn:append(101) => gn:to-array()

[2,3,4,5,6,101]

gn:empty-generator() => gn:append(101) => gn:to-array()

[101]

18.4.2.2 gn:chunk
Summary

Returns a new generator each of whose yield values is a "chunk" of consecutive values of the yield of the supplied $generator held in an array of size $size, with the possible exception that the size of the array containing the last "chunk" could be smaller.

Signature
gn:chunk(
$generatoras fn:generator,
$sizeas xs:positiveInteger
) as fn:generator
Properties

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

Rules

If the generator's yield doesn't contain any value, an empty generator (with empty yield) is returned.

Otherwise returns a new generator: Gnext, whose current-value is:

$generator => gn:take($size) => gn:to-array(), and upon which the function gn:next(Gnext) produces the same generator as:

$generator => gn:skip($size) => gn:chunk($size).

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
                else $generator
   return
     if($gen?end-reached) then gn:empty-generator()
     else
       let $thisChunk := gn:to-array(gn:take($gen, $size)),
           $cutGen := gn:skip($gen, $size),
           $resultGen := $gen => map:put("get-current", fn($this as f:generator){$thisChunk})
                              => map:put("move-next",   
                                         fn($this as f:generator){gn:chunk($cutGen, $size)})
        return $resultGen
Examples
ExpressionResult
gn:empty-generator() => gn:chunk(20) => gn:some()

false()

$gen2ToInf => gn:chunk(10) => gn:value()

[2,3,4,5,6,7,8,9,10,11]

(The first from an infinite number of chunks).

$gen2ToInf => gn:chunk(10) => gn:next() => gn:value()

[12,13,14,15,16,17,18,19,20,21]

(The second from an infinite number of chunks).

$gen2ToInf => gn:take(10) 
            => gn:chunk(4) => gn:to-array()

[[2,3,4,5],[6,7,8,9],[10,11]]

$gen2ToInf => gn:take(10) => gn:chunk(4) 
            => gn:for-each(fn($arr)
                      {array:size($arr)}) => gn:to-array()

[4,4,2]

18.4.2.3 gn:concat
Summary

Returns a new generator whose yield consists of the yield of $generator followed by the yield of $generator2.

Signature
gn:concat(
$generatoras fn:generator,
$generator2as fn:generator
) as fn:generator
Properties

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

Rules

This function produces a new generator whose yield consists of the yield of $generator followed by the yield of $generator2.

Thus, if the yield of $generator contains $M values, and the yield of $generator2 contains $N values.

The yield of the generator returned by the function: $result-generator contains $M + $N values, and:

$result-generator => gn:take($M) is a generator that has the same yield as $generator, and:

$result-generator => gn:skip($M) is a generator that has the same yield as $generator2.

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
			else $generator,
    $gen2 := if(not($generator2?initialized)) then $gen2 =?> move-next()
             else $generator2,
    $resultGen := if($gen?end-reached) then $gen2
                    else if($gen2?end-reached) then $gen
                         else
                           $gen  => map:put("move-next", 
                                            fn($this as f:generator)
                                              {
                                               let $nextGen := $gen =?> move-next()
                                                return 
                                                  gn:concat($nextGen, $gen2)
                                              }
                                           )                                   
 return 
   $resultGen
Examples
ExpressionResult
$gen2ToInf => gn:subrange(10, 15) 
            => gn:concat($gen2ToInf => gn:subrange(1, 9)) 
            => gn:to-array()
[11,12,13,14,15,16,
 2,3,4,5,6,7,8,9,10]
gn:empty-generator() 
            => gn:concat(gn:empty-generator()) 
            => gn:to-array()

[]

gn:empty-generator() 
            => gn:concat($gen2ToInf => gn:take(1)) 
            => gn:to-array()

[2]

$gen2ToInf => gn:take(1) 
            => gn:concat(gn:empty-generator()) 
            => gn:to-array()

[2]

$gen2ToInf => gn:concat($gen2ToInf) => gn:value()

[2]

18.4.2.4 gn:distinct
Summary

Returns a new generator whose yield contains only the distinct values from the original generator, in their original order.

Signature
gn:distinct(
$generatoras fn:generator
) as fn:generator
Properties

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

Rules

If the yield of $generator contains no values, that is: $generator => gn:some() is false(), then gn:empty-generator() is returned.

Otherwise, a generator is returned, the first value ($v1) of whose yield is the same as the first value of $generator, and the remaining values are the distinct values of the yield of the generator $generator => gn:filter(fn($x){not(deep-equal($v1, $x))})

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
              else $generator
 return
   if($gen?end-reached) then $gen
   else
     let $priorValue := $gen =?> get-current()
       return
         $gen => map:put("move-next", 
                         fn($this as f:generator)
                         {gn:distinct(gn:remove-where(gn:tail($gen), 
                                      fn($x){deep-equal($priorValue, $x)}
                                      ))})
Examples
ExpressionResult
gn:make-generator-from-sequence((1, 3, 1, 2, 1, 5, 3, 2))  
            => gn:distinct() => gn:to-array()

[1,3,2,5]

$gen2ToInf  
            => gn:for-each(fn($n){$n idiv 10}) 
            => gn:take(50) => gn:distinct() => gn:to-array()

[0,1,2,3,4,5]

$gen2ToInf  
            => gn:for-each(fn($n){$n idiv 10}) 
            => gn:take(100) => gn:distinct() => gn:to-array()
[0,1,2,3,4,5,
6,7,8,9,10]
$gen2ToInf  
            => gn:for-each(fn($n){$n idiv 10}) 
            => gn:distinct() => gn:take(12) => gn:to-array()
[0,1,2,3,4,5,
6,7,8,9,10,11]

(The first 12 distinct numbers from an infinite sequence.)

gn:empty-generator() => gn:distinct() => gn:to-array() 

[]

18.4.2.5 gn:filter
Summary

Returns a new generator whose yield contains exactly those values from the yield of the original generator, upon which the supplied predicate returns true(), in their original order.

Signature
gn:filter(
$generatoras fn:generator,
$predicateas fn(item()*) as xs:boolean
) as fn:generator
Properties

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

Rules

If the supplied generator's yield is empty, this same generator is returned.

If none of the values of the supplied generator's yield satisfies the $predicate, a generator with empty yield is returned.

Otherwise returns the concatenation of: a generator whose yield contains exactly one value - the first satisfying the predicate value (V1), and the second generator to be concatenated: the result of filtering with the same $predicate the generator whose yield has the same values as the original generator, but with all values preceding and including V1 - removed.

Formal Equivalent

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

declare function gn:filter($generator as f:generator, 
                           $predicate as function(item()*) as xs:boolean) 
                    as f:generator
{
 if($generator?initialized and $generator?end-reached) 
  then gn:empty-generator()
  else
    let $getNextGoodGen := function($gen as map(*), 
                                    $pred as function(item()*) as xs:boolean)
       {
          if($gen?end-reached) then gn:empty-generator()
          else
            let $mapResult := 
                  while-do(
                           $gen,
                           function($x) { not($x?end-reached) 
                                         and not($pred($x =?> get-current()))},
                           function($x) { $x =?> move-next() }
                           )   
            return 
              if($mapResult?end-reached) then gn:empty-generator()
               else $mapResult                  
       },
       
       $gen := if($generator?initialized) then $generator 
                 else $generator =?> move-next(),
       $nextGoodGen := $getNextGoodGen($gen, $pred)
    return
      if($nextGoodGen?end-reached) then gn:empty-generator()
      else
        $nextGoodGen  
	   => map:put("inputGen", $nextGoodGen)
	   => map:put("move-next", 
		      fn($this as f:generator) 
		      {
		        let $nextGoodGen := $getNextGoodGen($this?inputGen =?> move-next(), 
		                                            $pred)
		         return
		           if($nextGoodGen?end-reached) then gn:empty-generator()
		             else
		               $nextGoodGen => map:put("move-next",   
						       fn($this as f:generator) 
							{gn:filter($nextGoodGen 
							             =?> move-next(), $pred)})
					    => map:put("inputGen", $nextGoodGen)
		      }
			  )
  }
Examples
ExpressionResult
$gen2ToInf => gn:filter(fn($n){$n mod 2 eq 1}) => gn:value()

3

$gen2ToInf => gn:filter(fn($n){$n mod 2 eq 1}) 
          => gn:next() => gn:value()

5


$gen2ToInf => gn:filter(fn($n){$n mod 2 eq 1}) 
               => gn:take(7) => gn:to-array()
[3,5,7,9,
11, 13,15]

(The first 7 values of a filtered infinite generator.)


$gen2ToInf => gn:take(10) => gn:filter(fn($n){$n gt 12}) 
                 => gn:to-array()

[]


gn:empty-generator() => gn:filter(fn($n){$n eq $n}) => gn:to-array()

[]

18.4.2.6 gn:for-each
Summary

Produces a new generator, in the yield of which each value is the result of applying the function item $action on the corresponding value of the yield of the original $generator, in their original order.

Signature
gn:for-each(
$generatoras fn:generator,
$actionas fn(item()*) as item()*
) as fn:generator
Properties

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

Rules

If the yield of $generator has no values, then a generator, whose yield has no values, is returned.

Otherwise a generator is returned, whose current value is $generator => gn:value() => $action(), and whose move-next method produces $generator => gn:skip(1) => gn:for-each($action).

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
			else $generator        
return
 if($gen?end-reached) then gn:empty-generator()
  else
   let $current := $fun($gen =?> get-current()),
       $newResultGen := map:put($gen, 
                                "get-current",
                                fn($this as f:generator){$current}),
       $nextGen := $gen =?> move-next()
    return
	  if($nextGen?end-reached) then $newResultGen
	   else
	     let $newResultGen2 :=  map:put($newResultGen, "move-next",   
	                                    fn($this as f:generator) 
	                                    {gn:for-each($nextGen, $action)}) 
		   return
		     $newResultGen2
Examples
ExpressionResult
$gen2ToInf => gn:subrange(1, 5) => gn:for-each($double) => gn:to-array()

[4,6,8,10,12]

$gen2ToInf => gn:for-each($double) => gn:take(5) => gn:to-array()

[4,6,8,10,12]

(gn:for-each on an infinite generator).

gn:empty-generator() => gn:for-each($double) => gn:to-array()

[]

18.4.2.7 gn:for-each-pair
Summary

Produces a new generator, in the yield of which each value is the result of applying the function item $action on the corresponding values of the yields of $generator1 and $generator2, in their original order.

Signature
gn:for-each-pair(
$generator1as fn:generator,
$generator2as fn:generator,
$actionas fn(item()*, item()*) as item()*
) as fn:generator
Properties

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

Rules

If one or both provided generators has an empty yield (yield that contains no values), then the result is a generator that has an empty yield. Otherwise:

If the yield of $generator1 is: V11, V12, ..., V1n, and the yield of $generator2 is: V21, V22, ..., V2m,

then the result is a generator with yield that contains k = min(m, n) values:

$action(V11, V21), $action(V12, V22), ..., $action(V1k, V2k)))

Formal Equivalent

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

let $gen := if(not($generator1?initialized)) then $generator1 =?> move-next()
            else $generator1,
    $gen2 := if(not($generator2?initialized)) then $generator2 =?> move-next()
             else $generator2
return
  if($gen?end-reached or $gen2?end-reached) then gn:empty-generator() 
   else  
	 let $current := $fun($gen =?> get-current(), $gen2 =?> get-current()),
	     $newResultGen := map:put($gen, "get-current", 
	                              fn($this as f:generator){$current}),
	     $nextGen1 := $gen =?> move-next(),
	     $nextGen2 := $gen2 =?> move-next()
	  return
	    if($nextGen1?end-reached or $nextGen2?end-reached) then $newResultGen
	     else
	      let $newResultGen2 := map:put($newResultGen, "move-next",
                                            fn($this as f:generator)
                                            {gn:for-each-pair($nextGen1, $nextGen2, $action)})
	          return
	            $newResultGen2
Examples
ExpressionResult
$gen2ToInf => gn:subrange(1, 5) 
               => gn:for-each-pair($gen2ToInf => gn:subrange(6, 10), $sum2) 
               => gn:to-array()

[9,11,13,15,17]

$gen2ToInf => gn:for-each-pair($gen2ToInf, $sum2) 
               => gn:take(5) => gn:to-array()

[4,6,8,10,12]

(gn:for-each-pair applied on two infinite generators).

gn:empty-generator() 
               => gn:for-each-pair($gen2ToInf => gn:subrange(6, 10), $sum2) 
               => gn:to-array()

[]

18.4.2.8 gn:insert-at
Summary

Returns a generator whose yield contains the first $position - 1 values of the yield of $generator, followed by the supplied $value, followed by all the values of the yield of $generator starting from position $position.

Signature
gn:insert-at(
$generatoras fn:generator,
$positionas xs:positiveInteger,
$valueas item()*
) as fn:generator
Properties

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

Rules

If the yield of the $generator contains less that $position - 1 values, error [err:FOGR0002] is raised.

If the supplied $position is 1 then the function returns a generator whose yield is that of the supplied $generator, prepended by the provided $value.

Otherwise, the function returns a generator in whose yield the values at position from 1 to $position - 1 are the values from the yield of the original $generator at the same positions, the value at position $position in the returned generator's yield is the supplied $value, and the values in this yield after position $position are the same as the remaining values in the supplied $generator's yield starting at position $position.

Formal Equivalent

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

let $genTail := gn:skip-strict($generator, $position - 1, true())
 return
   if($position gt 1)
     then $generator => gn:take($position -1) => gn:append($value) => gn:concat($genTail)
     else $genTail => prepend($value)
Examples
ExpressionResult
$gen2ToInf => gn:insert-at(3, "XYZ") 
               => gn:take(10) => gn:to-array()

[2,3,"XYZ",4,5,6,7,8,9,10]

$gen2ToInf => gn:take(10) 
               => gn:insert-at(1, "ABC") => gn:to-array()

["ABC",2,3,4,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
               => gn:insert-at(11, "PQR") 
               => gn:to-array()

[2,3,4,5,6,7,8,9,10,11,"PQR"]

$gen2ToInf => gn:take(10) 
               => gn:insert-at(12, "GHI") 
               => gn:to-array()

Raises error FOGR0002.

18.4.2.9 gn:next
Summary

Produces the next state/generator-instance obtained from the current generator-instance $generator.

Signature
gn:next(
$generatoras fn:generator
) as fn:generator
Properties

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

Rules

If the generator's yield doesn't contain any value, error [err:FOGR0002] is raised.

Otherwise returns the next state/generator-instance obtained from the current generator-instance $generator

Note:

This function is a synonym for the generator method move-next. The goal is to free the end user from the nuisance of having to enter additional parentheses within an expression due to the different precedence of the =?> and => operators. Thus, instead of having to write:

($myGenerator => gn:take(5)) =?> move-next() => gn:head(), one simply writes:

$myGenerator => gn:take(5) => gn:next() => gn:head()

Formal Equivalent

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

$generator =?> move-next()
Examples
ExpressionResult
$gen2ToInf => gn:next()  instance of f:generator

true()

$gen2ToInf => gn:next()  => gn:head()

3

$gen2ToInf => gn:next()  => gn:next()  => gn:head()

4

gn:empty-generator() => gn:next()

Raises error FOGR0002.

18.4.2.10 gn:prepend
Summary

Returns a generator, whose yield is the supplied $value followed by the values of the yield of the supplied $generator.

Signature
gn:prepend(
$generatoras fn:generator,
$valueas item()*
) as fn:generator
Properties

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

Rules

A generator G0, whose yield contains a single value: $value is constructed.

Then the result of the concatenation of G0 and the supplied $generator is returned.

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
            else $generator,
    $genSingle := gn:empty-generator() => gn:append($value)
 return
    gn:concat($genSingle, $gen)
Examples
ExpressionResult
$gen2ToInf => gn:subrange(1, 5) 
            => gn:prepend(101) => gn:to-array()

[101,2,3,4,5,6]

$gen2ToInf => gn:prepend(999) 
            => gn:take(5) => gn:to-array()

[999,2,3,4,5]

gn:empty-generator() => gn:prepend(777) => gn:to-array()

[777]

18.4.2.11 gn:remove-at
Summary

Returns a generator, whose yield is the result of removing the $positionth value from the yield of the supplied $generator .

Signature
gn:remove-at(
$generatoras fn:generator,
$positionas xs:positiveInteger
) as fn:generator
Properties

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

Rules

If $position is greater than the number of values in the yield of the $generator, error FOGR0002 is raised.

Otherwise, returns the concatenation of two generators: one whose yield contains the first $position -1 values from the yield of the supplied $generator, and the second: whose yield contains all values at positions greater than $position from the yield of the supplied $generator.

Formal Equivalent

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

let $genTail := gn:skip-strict($generator, $position, true())
  return
	if($position gt 1)
	  then gn:concat(gn:take($generator, $position - 1), $genTail)
	  else $genTail
Examples
ExpressionResult
$gen2ToInf => gn:take(10) 
            => gn:remove-at(3) => gn:to-array()

[2,3,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:remove-at(1) => gn:to-array()

[3,4,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:remove-at(10) => gn:to-array()

[2,3,4,5,6,7,8,9,10]

$gen2ToInf => gn:remove-at(3) 
            => gn:take(10) => gn:to-array()

[2,3,5,6,7,8,9,10,11,12]

$gen2ToInf => gn:take(10) 
            => gn:remove-at(11) => gn:to-array()

Raises error FOGR0002.

18.4.2.12 gn:remove-where
Summary

Returns a generator whose yield is the result of removing from the yield of the supplied $generator all values upon which the supplied $predicate is true().

Signature
gn:remove-where(
$generatoras fn:generator,
$predicateas function(item()*) as xs:boolean
) as fn:generator
Properties

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

Rules

If the yield of the supplied $generator is empty, then this same generator is returned.

Otherwise a generator is returned whose yield is the result of filtering the yield of the supplied $generator with a function that returns true() exactly when the provided $predicate returns false().

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
             else $generator
  return
    gn:filter($gen, fn($x){not($predicate($x))})
Examples
ExpressionResult
$gen2ToInf => gn:remove-where(fn($x){$x mod 3 eq 0}) 
            => gn:take(10) => gn:to-array()

[2,4,5,7,8,10,11,13,14,16]

(Removed all matching values from an infinite generator).

gn:empty-generator() => gn:remove-where(fn($x){$x mod 3 eq 0})
                      => gn:to-array()

[]

18.4.2.13 gn:replace
Summary

Returns a generator, whose yield is the result of replacing in the yield of the supplied $generator the first value upon which the application of the supplied $predicate returns true() with the supplied $replacement .

Signature
gn:replace(
$generatoras fn:generator,
$predicateas function(item()*) as xs:boolean,
$replacementas item()*
) as fn:generator
Properties

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

Rules

If the yield of the provided $generator is empty, then $generator is returned.

If there is no value in the $generator's yield, upon which the application of the supplied $predicate returns true(), then the function returns the original $generator.

Otherwise, if the result of applying the $predicate on the first value of the $generator's yield is true(), then the function returns a generator the first value in whose yield is $replacement, and whose move-next() method produces a generator having the same yield as $generator =?> move-next()

If the result of applying the $predicate on the first value of the $generator's yield is false(), then the function returns a generator whose get-current() method is the same as that of the supplied $generator, and whose move-next() method returns the result of gn:replace on the generator returned by $generator =?> move-next() .

Formal Equivalent

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

if($generator?end-reached) then $generator
   else
    let $current := $generator =?> get-current()
     return
       if($predicate($current))
         then let $nextGen := $generator =?> move-next()
               return
                 $generator => map:put("get-current", fn($this as f:generator) {$replacement})
                            => map:put("move-next", fn($this as f:generator) { $nextGen })
         else (: $current is not the match for replacement :)
           let $nextGen := $generator =?> move-next()
            return  
              $generator => map:put("move-next", 
                                    fn($this as f:generator)
                                    {
                                      let $intendedReplace := 
                                             function($z) 
                                             {$z => gn:replace($funIsMatching, $replacement)}
                                       return
                                         if($nextGen?end-reached) then $nextGen
                                            else $intendedReplace($nextGen)
                                    }
                                   )
Examples
ExpressionResult
$gen2ToInf => gn:replace(fn($x)
                         {$x gt 4}, "Replacement")  
            => gn:take(10) => gn:to-array()

[2,3,4,"Replacement",6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:replace(fn($x){$x lt 3},
                          "Replacement") 
            => gn:to-array()

["Replacement",3,4,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:replace(fn($x){$x gt 10},
                          "Replacement") 
            => gn:to-array()

[2,3,4,5,6,7,8,9,10,"Replacement"]

$gen2ToInf => gn:take(10) 
            => gn:replace(fn($x){$x gt 11},
                          "Replacement") 
            => gn:to-array()

[2,3,4,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:replace(fn($x){$x lt 2},
                          "Replacement") 
            => gn:to-array()

[2,3,4,5,6,7,8,9,10,11]

$gen2ToInf => gn:take(10) 
            => gn:replace(fn($x){$x gt 4},
                          "Replacement") 
            => gn:to-array()

[2,3,4,"Replacement",6,7,8,9,10,11]

gn:empty-generator() 
            => gn:replace(fn($x){$x eq $x},
                          "Replacement") 
            => gn:to-array()

[]

18.4.2.14 gn:reverse
Summary

Returns a generator, the values of whose yield are the ones in the yield of the supplied $generator but in reverse order.

Signature
gn:reverse(
$generatoras fn:generator
) as fn:generator
Properties

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

Rules

If the yield of the provided $generator is empty, then $generator is returned.

Otherwise a generator is returned, whose yield is the result of appending the current value of the supplied $generator to the reversed yield of $generator => gn:tail() .

Formal Equivalent

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

if($generator?end-reached) then gn:empty-generator()
  else
   let $current := $generator =?> get-current()
    return
      gn:append(gn:reverse(gn:tail($generator)), $current)
Examples
ExpressionResult
gn:empty-generator() => gn:reverse() 
            => gn:to-array()

[]

gn:empty-generator() => gn:append(2)  
            => gn:reverse() => gn:to-array()

[2]

$gen2ToInf => gn:take(10) 
            => gn:reverse() => gn:to-array()

[11,10,9,8,7,6,5,4,3,2]

18.4.2.15 gn:scan-left
Summary

Returns a generator whose yield contains the partial results of the evaluation of the gn:fold-left function with the same arguments.

Signature
gn:scan-left(
$generatoras fn:generator,
$initas item()*,
$actionas fn(item()*, item()*) as item()*) as item()*
) as fn:generator
Properties

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

Rules

If the yield of $generator is empty, returns a generator whose yield contains a single value: the supplied $init.

Otherwise computes a partial result $partial-result equal to $action($init, $generator =?> get-current()), and a $next-generator, that is equal to $generator =?> move-next() and returns a generator, the first value of whose yield is $init, and the remaining values are the yield of the generator: gn:scan-left($next-generator, $partial-result, $action).

Formal Equivalent

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

declare function gn:scan-left($generator as f:generator, $init as item()*, $action as fn(*)) 
           as f:generator
{
  let $resultGen := gn:empty-generator() 
                         => map:put("end-reached", false())
                         => map:put("get-current",   fn($this as f:generator){$init})
   return
     if($generator?end-reached) 
       then $resultGen => map:put("move-next", fn($this as f:generator)
                                               {gn:empty-generator()})
       else
         let $resultGen := $resultGen => map:put("get-current", 
                                                 fn($this as f:generator){$init}),
             $partialFoldResult := $action($init, $generator =?> get-current())
           return
             let $nextGen := $generator =?> move-next()
              return
                $resultGen => map:put("move-next", fn($this as f:generator)
                                      { 
                                          gn:scan-left($nextGen, $partialFoldResult, $action)
                                       }
                                      )            
}
Examples
ExpressionResult
gn:empty-generator() 
         => gn:scan-left(0, fn($x, $y){$x + $y}) => gn:to-array()

[0]

$gen2ToInf => gn:take(5)  
         => gn:scan-left(0, fn($x, $y){$x + $y}) => gn:to-array()

[0,2,5,9,14,20]

$gen0toInf 
   => gn:for-each(fn($n)
                  {(2*$n + 1) div $factorial(2*xs:decimal($n))}) 
   => gn:take(8) 
   => gn:scan-left(0, fn($x, $y){$x + $y}) => gn:to-array()
[0,1,2.5,
 2.708333333333333333,
 2.718055555555555555,
 2.718278769841269841,
 2.718281801146384479,
 2.718281828286168563,
 2.718281828458229747]

(Infinite series summation: the partial sums from its first 8 steps.)

18.4.2.16 gn:scan-right
Summary

Returns a generator whose yield contains the partial results of the evaluation of the gn:fold-right function with the same arguments.

Signature
gn:scan-right(
$generatoras fn:generator,
$initas item()*,
$actionas fn(item()*, item()*) as item()*) as item()*
) as fn:generator
Properties

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

Rules

If the yield of $generator is empty, returns a generator whose yield contains a single value: the supplied $init.

Otherwise returns the reversed yield of gn:scan-left(gn:reverse($generator), $init, $action).

Formal Equivalent

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

gn:reverse(gn:scan-left(gn:reverse($gen), $init, $action))
Examples
ExpressionResult
gn:empty-generator() 
       => gn:scan-right(0, fn($x, $y){$x + $y}) => gn:to-array()

[0]

$genN => gn:take(10) 
       => gn:scan-right(0, fn($x, $y){$x + $y}) => gn:to-array()
[55,54,52,49,45,
 40,34,27,19,10,0]
18.4.2.17 gn:skip
Summary

Returns a generator whose yield contains only the values of the yield of the supplied $generator after the $nth one and in their original order.

Signature
gn:skip(
$generatoras fn:generator,
$nas xs:nonNegativeInteger
) as fn:generator
Properties

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

Rules

If $n is 0, the function returns the same supplied $generator.

If $n is greater than the number of values of the supplied $generator, the function returns an empty generator.

Otherwise the function returns the result of $generator => gn:next() => gn:skip($n -1).

Formal Equivalent

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

gn:skip-strict($gen, $n, false())
Examples
ExpressionResult
$gen2ToInf => gn:skip(7) instance of f:generator

true()

$gen2ToInf => gn:take(3) => gn:skip(2) => gn:to-array()

[4]

$gen2ToInf => gn:take(10) => gn:skip(10) => gn:to-array()

[]

$gen2ToInf => gn:take(10) => gn:skip(11) => gn:to-array()

[]

$gen2ToInf => gn:take(10) => gn:skip(9) => gn:to-array()

[11]

18.4.2.18 gn:skip-strict
Summary

Returns a generator whose yield contains the values of the yield of the supplied $generator after the $nth one. If the yield of the supplied $generator contains less than $n values, and the supplied argument $raise-error-on-empty is true() then [err:FOGR0002] is raised.

Signature
gn:skip-strict(
$generatoras fn:generator,
$nas xs:nonNegativeInteger,
$raise-error-on-emptyas xs:boolean
) as fn:generator
Properties

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

Rules

If $n is 0, the function returns the same supplied $generator.

If $n is greater than the number of values of the supplied $generator, and the supplied argument $raise-error-on-empty is true() then [err:FOGR0002] is raised, otherwise ($raise-error-on-empty is false()) the function returns an empty generator.

Otherwise the function returns the result of $generator => gn:next() => gn:skip-strict($n -1, $raise-error-on-empty).

Formal Equivalent

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

declare function gn:skip-strict($gen as f:generator, 
                                $n as xs:nonNegativeInteger, 
                                $issueErrorOnEmpty as xs:boolean) as f:generator
{
  if($n eq 0) then $generator
    else if($generator?end-reached) 
           then if($issueErrorOnEmpty)
                 then error((), "Input Generator too-short") 
                 else gn:empty-generator()
    else 
      let $gen := if(not($generator?initialized)) then $generator =?> move-next()
                   else $generator
        return
          if(not($gen?end-reached)) 
            then gn:skip-strict($gen =?> move-next(), $n -1, $issueErrorOnEmpty)
            else gn:empty-generator()    
};
Examples
ExpressionResult
$gen2ToInf => gn:skip-strict(7, true()) instance of f:generator

true()

$gen2ToInf => gn:take(3) => gn:skip-strict(2, true()) => gn:to-array()

[4]

$gen2ToInf => gn:take(10) => gn:skip-strict(10, true()) => gn:to-array()

[]

$gen2ToInf => gn:take(10) => gn:skip-strict(11, false()) => gn:to-array()

[]

$gen2ToInf => gn:take(10) => gn:skip-strict(11, true()) => gn:to-array()

Raises error FOGR0002.

18.4.2.19 gn:skip-while
Summary

Returns a new generator whose yield contains all the values from the yield of the supplied $generator, having removed the longest leading segment of values on which the supplied $predicate returns true().

Signature
gn:skip-while(
$generatoras fn:generator,
$predicateas fn(item()*) as xs:boolean
) as fn:generator
Properties

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

Rules

If the yield of the supplied $generator is empty the function returns the same $generator.

If $predicate($generator => gn:value()) is false(), the function returns the same $generator.

Otherwise the function returns gn:skip-while($generator =?> move-next(), $predicate).

Formal Equivalent

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

declare function gn:skip-while($generator as f:generator, 
                               $predicate as function(item()*) as xs:boolean) 
           as f:generator
{
  let $gen := if(not($generator?initialized)) then $generator =?> move-next()
                else $generator
   return
     if($gen?end-reached) then gn:empty-generator()
      else
        let $current := $gen =?> get-current()
         return
           if(not($predicate($current))) then $gen
            else gn:skip-while($gen =?> move-next(), $pred)  
}
Examples
ExpressionResult
$gen2ToInf => gn:skip-while(fn($n){$n lt 11}) 
            => gn:take(5) => gn:to-array()

[11,12,13,14,15]

$gen2ToInf => gn:skip-while(fn($n){$n lt 2})
            => gn:take(5) => gn:to-array()

[2,3,4,5,6]

gn:empty-generator() 
            => gn:skip-while(fn($n){$n lt 100}) => gn:to-array()

[]

18.4.2.20 gn:subrange
Summary

Returns a new generator whose yield contains the values from the yield of the original $generator, from position $start to position $endin their original order.

Signature
gn:subrange(
$generatoras fn:generator,
$startas xs:positiveInteger,
$endas xs:positiveInteger
) as fn:generator
Properties

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

Rules

If $start is greater than the number of values in the yield of the $generator then the function returns an empty generator.

If $start is greater than $end then the function returns an empty generator.

Otherwise, if the number of values in the yield of the supplied$generator is $gen-size, the function produces a generator, whose yield starts with the $startth value in the yield of the supplied$generator and ends with the min($gen-size, $end - $start + 1)th value of this yield.

Formal Equivalent

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

gn:take(gn:skip($generator, $start - 1), $end - $start + 1)
Examples
ExpressionResult
$gen2ToInf => gn:subrange(4, 6) => gn:to-array()

[5,6,7]

$gen2ToInf => gn:take(10) => gn:subrange(3, 13) 
            => gn:to-array()

[4,5,6,7,8,9,10,11]

gn:empty-generator() => gn:subrange(1, 1) => gn:to-array()

[]

$gen2ToInf => gn:take(10) => gn:subrange(5, 3) 
            => gn:to-array()

[]

18.4.2.21 gn:tail
Summary

Returns a new generator whose yield contains all the values but the first from the yield of the original $generator or raises [err:FOGR0002] if the supplied generator's yield is empty.

Signature
gn:tail(
$generatoras fn:generator
) as fn:generator
Properties

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

Rules

If the yield of the $generator is empty, the function raises [err:FOGR0002].

Otherwise the function returns a new generator, having as yield the yield of $generator with the first value skipped.

Formal Equivalent

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

gn:skip-strict($generator, 1, true())
Examples
ExpressionResult
$gen2ToInf => gn:tail() => gn:head()

3

$gen2ToInf => gn:subrange(4, 6) => gn:tail() 
            => gn:to-array()

[6, 7]

gn:empty-generator() => gn:tail() => gn:to-array()

Raises error FOGR0002.

18.4.2.22 gn:take
Summary

Returns a new generator whose yield is the leading segment with length $n from the yield of the original $generator or raises [err:FOGR0002] if the supplied generator's yield is empty and $n is greater than 0.

Signature
gn:take(
$generatoras fn:generator,
$nas xs:nonNegativeInteger
) as fn:generator
Properties

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

Rules

If $n eq 0 the function returns an empty generator.

If the yield of $generator is empty the function returns an empty generator.

If the yield of $generator contains less than $n values, the function returns $generator.

Otherwise the function returns a generator, whose yield's only value is the first value of the $generator's yield, concatenated with $generator => gn:next() => gn:take($n - 1) .

Formal Equivalent

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

declare function gn:take($generator as f:generator, $n as xs:integer) as f:generator
{
  let $gen := if(not($generator?initialized)) then $generator =?> move-next()
                else $generator
   return
     if($gen?end-reached or $n le 0) then gn:empty-generator()
      else
        let $current := $gen =?> get-current(),
            $newResultGen := map:put($gen, "get-current", fn($this as f:generator){$current}),
            $nextGen := $gen =?> move-next()
         return
           if($nextGen?end-reached) then $newResultGen
             else
              let
               $newResultGen2 :=  map:put($newResultGen, 
                                          "move-next", 
                                          fn($this as f:generator) 
                                          {gn:take($nextGen, $n -1)}) 
                 return
                   $newResultGen2  
}
Examples
ExpressionResult
$gen2ToInf => gn:take(5) instance of f:generator

true()

$gen2ToInf => gn:take(3) => gn:to-array()

[2,3,4]

$gen2ToInf => gn:take(100000000) 
            => gn:value()

2

(Take 100 million numbers and then get the first of these - fast, with no delay.)

gn:empty-generator() => gn:take(5) => gn:to-array()

[]

18.4.2.23 gn:take-while
Summary

Returns a new generator whose yield contains the longest leading segment from the yield of the original $generator on all values of which the provided function $predicate returns true().

Signature
gn:take-while(
$generatoras fn:generator,
$predicateas fn(item()*) as xs:boolean
) as fn:generator
Properties

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

Rules

If the yield of $generator is empty the function returns an empty generator.

If the the application of the $predicate on the first value of the yield of $generator is false() the function returns an empty generator.

Otherwise the function returns a generator whose yield id the concatenation of the first value of the yield of $generator with $generator => gn:next() => gn:take-while($predicate).

Formal Equivalent

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

declare function gn:take-while($generator as f:generator, 
                               $predicate as function(item()*) as xs:boolean) 
                    as f:generator
{
  let $gen := if(not($generator?initialized)) then $generator =?> move-next()
                else $generator
   return
     if($gen?end-reached) then gn:empty-generator()
      else      
        let $current := $gen =?> get-current()
          return
            if(not($predicate($current))) then gn:empty-generator()
            else
              let $newResultGen := map:put($gen, "get-current", 
                                           fn($this as f:generator){$current}),
                  $nextGen := $gen =?> move-next()
               return
                  if($nextGen?end-reached) then $newResultGen
                  else
                    let $newResultGen2 :=  map:put($newResultGen, "move-next", 
                                                   fn($this as f:generator)
                                                   {gn:take-while($nextGen, $pred)}) 
                     return $newResultGen2    
}
Examples
ExpressionResult
$gen2ToInf => gn:take-while(fn($n){$n lt 11}) 
            => gn:to-array()

[2,3,4,5,6,7,8,9,10]

$gen2ToInf => gn:take-while(fn($n){$n lt 2}) 
            => gn:to-array()

[]

gn:empty-generator() 
            => gn:take-while(fn($n){$n lt 2}) => gn:to-array()

[]

$gen2ToInf 
            => gn:take-while(fn($n){$n lt 100000000}) => gn:value()

2

(Take all numbers less than 100 million and then get the first of these - fast, with no delay.)

18.4.2.24 gn:zip
Summary

Returns a new generator the kth value of whose yield is an array having two members: the kth value of the yield of $generator1 and the kth value of the yield of $generator2, where kdoes not exceed the smaller of the lengths of the yields of the two generators.

Signature
gn:zip(
$generator1as fn:generator,
$generator2as fn:generator
) as fn:generator
Properties

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

Rules

If any of the yields of the two provided generators: $generator1 and $generator2 is empty, the function returns an empty generator.

Otherwise the function returns the result of:

gn:for-each-pair($generator1, $generator2, fn($x1, $x2){[$x1, $x2]}) .

Formal Equivalent

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

gn:for-each-pair($generator1, $generator2, fn($x1, $x2){[$x1, $x2]})
Examples
ExpressionResult
gn:zip($gen2ToInf => gn:subrange(1, 5),
        $gen2ToInf => gn:subrange(6, 10)) 
        => gn:to-array()

[[2,7],[3,8],[4,9],[5,10],[6,11]]

gn:zip($gen2ToInf,
        $gen2ToInf => gn:skip(5)) 
        => gn:take(10) => gn:to-array()

[[2,7],[3,8],[4,9],[5,10],[6,11],[7,12],[8,13],[9,14],[10,15],[11,16]]

gn:zip(gn:empty-generator(),
        $gen2ToInf => gn:subrange(6, 10)) 
        => gn:to-array()

[]

18.4.3 Functions that produce a generator from a data provider

The functions in this section construct generators whose yield is supplied by an external provider function. Providers allow generators to expose yields that are too large to fit into memory, must be computed incrementally, or require access to external systems (such as files, databases, or web services).

A provider function is responsible for producing, on each invocation, both:

  1. state-data - an array with information required for the provider to compute its next result, and

  2. result-data - an array either containing a single yield-value or empty, signaling that the data for producing the yield has been exhausted.

The generator returned by these functions behaves identically to any other generator: values are not computed eagerly but are obtained only as result of evaluating the method move-next() followed by the evaluation of the method get-current().

FunctionMeaning
gn:empty-generatorReturns a new generator whose yield does not contain any values.
gn:make-generatorReturns a generator, the values of whose yield are obtained by consecutive calls to a supplied $provider function.
gn:make-generator-from-arrayReturns a generator, the values of whose yield are the values of the supplied $input array.
gn:make-generator-from-sequenceReturns a generator, the values of whose yield are the values of the supplied $input sequence.
gn:make-generator-from-mapReturns a generator, whose yield is the sequence of all single map entries of the supplied $input map.
18.4.3.1 gn:empty-generator
Summary

Returns a new generator whose yield does not contain any values.

Signature
gn:empty-generator() as fn:generator
Properties

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

Rules

Returns a new generator whose yield does not contain any values.

The initialized and end-reached fields of the result are both set to true().

Formal Equivalent

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

f:generator(initialized := true(), end-reached := true(),
            get-current := fn($this as f:generator)
                           {error(QName('http://www.w3.org/2005/xqt-errors', 'err:FOGR0002'),
                            "get-current() called on an empty-generator")},
            move-next := fn($this as f:generator)
                           {error(QName('http://www.w3.org/2005/xqt-errors', 'err:FOGR0002'),
                            "move-next() called on an empty-generator")},
            )
Examples
ExpressionResult
gn:empty-generator() => gn:to-array()

[]

gn:empty-generator() => gn:to-array() => array:empty()

true()

18.4.3.2 gn:make-generator
Summary

Returns a generator, the values of whose yield are obtained by consecutive calls to a supplied $provider function.

Signature
gn:make-generator(
$provideras function(array(*)) as array(*)
) as fn:generator
Properties

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

Rules

The $provider function is called to get the first value of the yield of the result-generator. It accepts as argument an array, that contains data, referred to as "state-data" here, necessary to identify and return its next result. On the first call to the $provider, an empty array is passed as the state-data.

The $provider returns an array with two members. The first member is the state-data to be passed to it on the next call. The second member is an array, containing the current value of the result-generator.

To signal that there are no more yield-values to be returned the $provider returns an empty array as its result's second member. When this happens no more calls to the $provider are made and the move-next method of the current result-generator-instance is set to return an empty generator.

If the $provider returns a non-empty array as its result's second member, the value of the single member of this non-empty array is set to be returned by the get-current method of the current result-generator instance and the move-next method of the current result-generator instance is specified in such a way that, when it is called, it would itself call the $provider with the latest returned state-data and based on the return of that call would construct correctly the next result-generator instance.

Formal Equivalent

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

let $gen := if(not($generator?initialized)) then $generator =?> move-next()
              else $generator,
    $providerResult := $provider([]),
    $nextProviderState := $providerResult(1),
    $nextDataItemHolder := $providerResult(2)
 return
    let $nextGen := if(array:empty($nextDataItemHolder)) 
                      then gn:empty-generator()  
                      else gn:empty-generator()
                      => map:put("providerState", $nextProviderState)
                      => map:put("current", $nextDataItemHolder(1))
                      => map:put("end-reached", false())
                      => map:put("get-current", fn($this as f:generator) {$this?current})
                      => map:put("move-next",  
                                 fn($this as f:generator) 
                                 {
                                  let $nextProviderResult := $provider($this?providerState),
                                      $nextDataItemHolder := $nextProviderResult(2)
                                    return
                                      if(array:empty($nextDataItemHolder)) 
                                        then gn:empty-generator()
                                        else
                                          $this => map:put("current", $nextDataItemHolder(1))
                                                => map:put("providerState", 
                                                           $nextProviderResult(1))
                                 }
                                )
                             
    return $nextGen
Examples
ExpressionResult

gn:make-generator(fn($state as array(*))
                 {
                  let $numGenerated := if(array:empty($state)) then 0
                                       else $state[1]
                   return
                      if($numGenerated le 9) 
                      then [ [$numGenerated + 1], [$numGenerated + 1] ]
                      else [[-1], []]
                 } 
                 ) => gn:to-array()
[1,2,3,4,5,6,
7,8,9,10]

gn:make-generator(fn($state as array(*))
                {
                  let $numGenerated := if(array:empty($state)) then 0
                                       else $state[1]
                    return
                      [ [$numGenerated + 1], [$numGenerated + 1] ]
                } 
                 ) => gn:value()

1

(Make a generator from an infinite provider, then get its first value - immediately , with no delay.)


gn:make-generator(fn($state as array(*))
                {
                  let $numGenerated := if(array:empty($state)) then 0
                                       else $state[1]
                    return
                      [ [$numGenerated + 1], [$numGenerated + 1] ]
                } 
                 ) => gn:subrange(10, 15) => gn:to-array()

[10,11,12,13,14,15]

(Get a subrange of values from a generator created with an infinite provider - immediately , with no delay.)

18.4.3.3 gn:make-generator-from-array
Summary

Returns a generator, the values of whose yield are the values of the supplied $input array.

Signature
gn:make-generator-from-array(
$inputas array(*)
) as fn:generator
Properties

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

Rules

The function uses a provider function, whose state-data is the last-processed array index, and whose result is the new state-data and the $input array's value at the next index.

If the supplied $input array is empty, the function returns an empty generator.

Otherwise, it calls gn:make-generator, passing to it the so constructed provider-function, and returns the result of this call.

Formal Equivalent

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

let $size := array:size($input),
      $arrayProvider := fn($state as array(xs:integer?))
                        {
                          let $ind := if(array:empty($state))
                                      then 0
                                      else $state(1),
                              $newState := if($ind +1 gt $size) then []   
                                             else [$ind +1],
                              $newResult := if($ind +1 gt $size) then []
                                              else [$input($ind + 1)]
                           return [$newState, $newResult]
                        }
   return gn:make-generator($arrayProvider)
Examples
ExpressionResult

gn:make-generator-from-array([1, 4, 9, 16, 25]) 
           instance of f:generator

true()


gn:make-generator-from-array([1, 4, 9, 16, 25]) => gn:to-array()

[1,4,9,16,25]


gn:make-generator-from-array([]) => gn:to-array()

[]

18.4.3.4 gn:make-generator-from-sequence
Summary

Returns a generator, the values of whose yield are the values of the supplied $input sequence.

Signature
gn:make-generator-from-sequence(
$inputas item()*
) as fn:generator
Properties

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

Rules

The function uses a provider function, whose state-data is the last-processed sequence position, and whose result is the new state-data and the value of the $input sequence at the next position.

If the supplied $input sequence is empty, the function returns an empty generator.

Otherwise, it calls gn:make-generator, passing to it the so constructed provider-function, and returns the result of this call.

Formal Equivalent

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

let $size := count($input), 
    $seqProvider := fn($state as array(xs:integer?))
                      {
                          let $ind := if(array:empty($state))
                                      then 0
                                      else $state(1),
                              $newState := if($ind +1 gt $size) then []   
                                             else [$ind +1],
                              $newResult := if($ind +1 gt $size) then []
                                              else [$input[$ind + 1]] 
                           return [$newState, $newResult]                  
                       }
   return gn:make-generator($seqProvider)
Examples
ExpressionResult

gn:make-generator-from-sequence((1, 8, 27, 64, 125)) 
      instance of f:generator

true()


gn:make-generator-from-sequence(()) => gn:to-array()

[]


gn:make-generator-from-sequence((1, 8, 27, 64, 125)) => gn:to-array()

[1,8,27,64,125]

18.4.3.5 gn:make-generator-from-map
Summary

Returns a generator, whose yield is the sequence of all single map entries of the supplied $input map.

Signature
gn:make-generator-from-map(
$inputas map(*)
) as fn:generator
Properties

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

Rules

The function uses a provider function, whose state-data is the position of the last-processed map key, and whose result is the new state-data and the single-entry of the $input map for the next key of the map.

If the supplied $input map is empty, the function returns an empty generator.

Otherwise, it calls gn:make-generator, passing to it the so constructed provider-function, and returns the result of this call.

Formal Equivalent

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

let $keys := map:keys($inputMap),
    $size := map:size($inputMap),
    $mapProvider := fn($state as array(xs:integer?))
    {	
	let $ind := if(array:empty($state))
                   then 0
                   else $state(1),
	    $newState := if($ind +1 gt $size) then []   
                         else [$ind +1],
	    $newResult := if($ind +1 gt $size) then []
                          else
                           let $key := $keys[$ind + 1]
                            return
                              [map:entry($key, $inputMap($key))]
        return [$newState, $newResult]                                      
     }                        
 return gn:make-generator($mapProvider)
Examples
ExpressionResult

let $myMap := {"John": 22, "Ann": 28, "Peter": 31}
 return 
   gn:make-generator-from-map($myMap) => gn:to-array()
[{"John":22},
{"Ann":28},
{"Peter":31}]

 let $myMap := {"John": 22, "Ann": 28, "Peter": 31},
     $genMap := gn:make-generator-from-map($myMap)
  return
     $genMap => gn:to-map()
{"John":22,
"Ann":28,
"Peter":31}

let $myMap := {}
 return 
   gn:make-generator-from-map($myMap) => gn:to-array()

[]


let $myMap := {}
 return 
   gn:make-generator-from-map($myMap) => gn:to-map()()

{}

18.4.4 Functions that produce an XPath collection from a generator

Generators can be used to construct standard XPath collections: arrays, maps, and sequences.

FunctionMeaning
gn:to-arrayReturns an array, whose members are the values of the yield of the supplied $generator.
gn:to-mapReturns a map, whose single entries (key-value pairs) are obtained from the values of the yield of the supplied $generator.
gn:to-sequenceReturns a sequence, whose items are obtained from the values of the yield of the supplied $generator.
18.4.4.1 gn:to-array
Summary

Returns an array, whose members are the values of the yield of the supplied $generator.

Signature
gn:to-array(
$generatoras fn:generator
) as array(*)
Properties

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

Rules

If the supplied $generator has an empty yield, or is not initialized, the function returns an emprty array.

Otherwise, starting from an empty array-result, the function appends to it every value contained in the yield of the $generator until there are no more values in the yield. Then, this array-result is returned.

Formal Equivalent

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

while-do( [$generator, []],
	  function( $in-out-args) 
	  { $in-out-args(1)?initialized and not($in-out-args(1)?end-reached) },
	  function($in-out-args) 
	           { array{$in-out-args(1) =?> move-next(), 
	             array:append($in-out-args(2), $in-out-args(1) =?> get-current())
	           }
	   }
) (2)
Examples
ExpressionResult

gn:empty-generator() => gn:to-array()

[]


$gen2ToInf => gn:take(3) 
           => gn:to-array() instance of array(*)

true()


 $gen2ToInf => gn:take(3) => gn:to-array()

[2,3,4]

18.4.4.2 gn:to-map
Summary

Returns a map, whose single entries (key-value pairs) are obtained from the values of the yield of the supplied $generator.

Signature
gn:to-map(
$generatoras fn:generator
) as map(*)
Properties

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

Rules

If the supplied $generator has an empty yield the function returns an empty map.

If the yield of the supplied $generator contains a value that is not a map-entry, an error is raised.

Otherwise the function returns a map all single-map-entries of which are the values of the yield of the supplied $generator.

Formal Equivalent

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

map:merge($generator => gn:to-sequence())
Examples
ExpressionResult
gn:empty-generator() => gn:to-map()

{}

let $myMap := {}
  return 
    gn:make-generator-from-map($myMap) => gn:to-map()

{}

let $myMap := {"John": 22, "Ann": 28, "Peter": 31},
    $genMap := gn:make-generator-from-map($myMap)
  return
    $genMap => gn:to-map()
{"John":22,"Ann":28,
"Peter":31}
$gen2ToInf => gn:take(10) => gn:to-map()

Raises error FORG0006.

(Because the values are not map-entries.)

$gen2ToInf => gn:take(10) => gn:chunk(2) 
            => gn:for-each(fn($chunk)
                          {map:entry($chunk(1), $chunk(2))})
            =>   gn:to-map()

{2:3,4:5,6:7,8:9,10:11}

18.4.4.3 gn:to-sequence
Summary

Returns a sequence, whose items are obtained from the values of the yield of the supplied $generator.

Signature
gn:to-sequence(
$generatoras fn:generator
) as item(*)
Properties

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

Rules

This function obtains and outputs every value of the yield of the supplied $generator

An empty sequence is returned if the supplied $generator has an empty yield.

Any value from the yield of the supplied $generator that is an empty sequence, is not represented in the result returned by the function.

Formal Equivalent

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

gn:to-array($generator) => array:items()
Examples
ExpressionResult
gn:empty-generator() => gn:to-sequence()

()

$gen2ToInf => gn:filter(fn($n){$n mod 2 eq 1}) 
            => gn:take(10) => gn:to-sequence()

(3,5,7,9,11,13,15,17,19,21)

gn:make-generator-from-array([(),1,(),2,(),3]) 
            => gn:to-sequence()

(1, 2, 3)

(Every value that is an empty sequence is not present in the result.)

1819 Dynamic evaluation

The following functions allow dynamic loading and evaluation of XQuery queries, XSLT stylesheets, and XPath binary operators.

FunctionMeaning
fn:load-xquery-moduleProvides access to the public functions and global variables of a dynamically loaded XQuery library module.
fn:transformInvokes a transformation using a dynamically loaded XSLT stylesheet.
fn:opReturns a function whose effect is to apply a supplied binary operator to two arguments.

18.119.1 Record fn:load-xquery-module-record

This record type is used to hold the result of the fn:load-xquery-module function.

NameMeaning

variables

This map (V ) contains one entry for each public global variable declared in the library module. The key of the entry is the name of the variable, as an xs:QName value; the associated value is the value of the variable.

  • Type: map(xs:QName, item()*)

functions

This map (F ) contains one entry for each distinct QName Q that represents the name of a public and non-external function declared in the library module. The key of the entry is Q, as an xs:QName value; the associated value is a map A. This map (A) contains one entry for each arity N within the arity range of any of the function declarations with the given name; its key is N, as an xs:integer value, and its associated value is a function item obtained as if by evaluating a named function reference Q#N, using the static and dynamic context of the call on fn:load-xquery-module. The function item can be invoked using the rules for dynamic function invocation.

  • Type: map(xs:QName, map(xs:integer, function(*)))

18.219.2 fn:load-xquery-module

Changes in 4.0 (next | previous)

  1. It has been clarified that loading a module has no effect on the static or dynamic context of the caller.  [Issue 725 PR 727 10 October 2023]

  2. The return type is now specified more precisely.  [Issue 883 PR 1072 19 March 2024]

  3. A new option is provided to allow the content of the loaded module to be supplied as a string.  [Issue 1329 PR 1333 22 July 2024]

Summary

Provides access to the public functions and global variables of a dynamically loaded XQuery library module.

Signature
fn:load-xquery-module(
$module-urias xs:string,
$optionsas map(*)?:= {}
) as load-xquery-module-record
Properties

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

Rules

The function loads an implementation-defined set of modules having the target namespace $module-uri.

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The $options argument can be used to control the way in which the function operates. The option parameter conventions apply.

If the query module is retrieved as an external resource, this is subject to the trust levelXP of the calling code. In addition, the ability of the loaded query module to access additional resources is subject to the value of the supplied trusted option.

Note:

Versions of XQuery prior to 4.0 do not define any constraints on access to external resources. Many XQuery implementations, however, provide such mechanisms. An implementation of fn:load-xquery-module that allows execution of an untrustedXP query must ensure that the ability of that query to access resources is appropriately restricted, regardless of the version of XQuery in use.

record(
xquery-version?as xs:decimal,
trusted?as xs:boolean,
location-hints?as xs:string*,
content?as xs:string?,
context-item?as item()?,
variables?as map(xs:QName, item()*),
vendor-options?as map(xs:QName, item()*)
)
KeyValueMeaning

xquery-version?

The minimum level of the XQuery language that the processor must support.
  • Type: xs:decimal

  • Default: The version given in the prolog of the library module; or implementation-defined if this is absent.

trusted?

Indicates whether the returned query module is trusted to access external resources. This applies both to resources statically referenced in the query module (such as imported schemas and imported library modules), and to resources accessed dynamically by invoking functions in the retrieved module, for example by use of the fn:doc function.
  • Type: xs:boolean

  • Default: false()

trueThe loaded query has the same level of trust as the caller, and may therefore access all external resources available to the caller.
falseThe functions and variables in the returned XQuery module are untrustedXP, and are therefore unable to access external resources unless these have been made explicitly available by a trusted caller.

location-hints?

A sequence of URIs (in the form of xs:string values) which may be used or ignored in an implementation-defined way.
  • Type: xs:string*

  • Default: Empty sequence

content?

The content of the query module as a string. When this option is used, the location-hints option is ignored. The static base URI of the dynamically loaded module is the same as the executable base URIXP of the caller.
  • Type: xs:string?

  • Default: Empty sequence

context-item?

The item to be used as the initial context item when evaluating global variables in the library module. Supplying an empty sequence is equivalent to omitting the entry from the map, and indicates the absence of a context item. If the library module specifies a required type for the context item, then the supplied value must conform to this type, without conversion.
  • Type: item()?

  • Default: Absent

variables?

Values for external variables defined in the library module. Values must be supplied for external variables that have no default value, and may be supplied for external variables that do have a default value. The supplied value must conform to the required type of the variable, without conversion. The map contains one entry for each external variable: the key is the variable’s name, and the associated value is the variable’s value. The option parameter conventions do not apply to this contained map.
  • Type: map(xs:QName, item()*)

  • Default: An empty map

vendor-options?

Values for vendor-defined configuration options for the XQuery processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XQuery processor. The meaning of the associated value is implementation-defined. Implementations should ignore options whose names are in an unrecognized namespace. The option parameter conventions do not apply to this contained map.
  • Type: map(xs:QName, item()*)

  • Default: An empty map

The result of the function is a map R with two entries, as defined in 18.119.1 Record fn:load-xquery-module-record.

The static and dynamic context of the library module are established according to the rules in C Context Components XQ31.

It is implementation-defined whether constructs in the library module are evaluated in the same execution scope as the calling module.

The library module that is loaded may import other modules using an import module declaration. The result of fn:load-xquery-module does not include global variables or functions declared in such a transitively imported module. However, the options map supplied in the function call may (and if no default is defined, must) supply values for external variables declared in transitively loaded library modules.

The library module that is loaded may import schema declarations using an import schema declaration. It is implementation-defined whether schema components in the in-scope schema definitions of the calling module are automatically added to the in-scope schema definitions of the dynamically loaded module. The in-scope schema definitions of the calling and called modules must be consistent, according to the rules defined in 2.2.5 Consistency Constraints XQ31.

Where nodes are passed to or from the dynamically loaded module, for example as an argument or result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XQuery implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotations, and about its relationships to other nodes passed across the interface.

Error Conditions

If $module-uri is a zero length string, a dynamic error is raised [err:FOQM0001].

If the implementation is not able to find a library module with the specified target namespace, an error is raised [err:FOQM0002].

If a static error (including a statically detected type error) is encountered when processing the library module, a dynamic error is raised [err:FOQM0003].

If a value is supplied for the initial context item or for an external variable and the value does not conform to the required type declared in the dynamically loaded module, a dynamic error is raised [err:FOQM0005].

If no suitable XQuery processor is available, a dynamic error is raised [err:FOQM0006]. This includes (but is not limited to) the following cases:

  1. No XQuery processor is available;

  2. Use of the function has been disabled;

  3. No XQuery processor supporting the requested version of XQuery is available;

  4. No XQuery processor supporting the optional Module Feature is available.

If a dynamic error (including a dynamically detected type error) is encountered when processing the module (for example, when evaluating its global variables), the dynamic error is returned as is.

Notes

If a function declaration F in the loaded module declares (say) four parameters of which one is optional, its arity range will be from 3 to 4, so the result will include two function items corresponding to F#3 and F#4. In the lower-arity function item, F#3, the fourth parameter will take its default value. If the expression that initializes the default value is context sensitive, the static and dynamic context for its evaluation are the static and dynamic contexts of the fn:load-xquery-module function call itself.

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support XQuery modules using a specified version of XQuery.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality.

The load-xquery-module function does not modify the static or dynamic context. Functions and variables from the loaded module become available within the result returned by the function, but they are not added to the static or dynamic context of the caller. This means, for example, that function-lookup will not locate functions from the loaded module.

Examples
Expression:
let $expr := "2 + 2"
let $module := `
  xquery version "4.0"; 
  module namespace dyn="http://example.com/dyn";
  declare %public variable $dyn:value := { $expr };
`
let $exec := load-xquery-module(
  "http://example.com/dyn",
  { 'content':$module }
)
let $variables := $exec?variables
return $variables( #Q{http://example.com/dyn}value )
Result:
4

18.319.3 fn:transform

Summary

Invokes a transformation using a dynamically loaded XSLT stylesheet.

Signature
fn:transform(
$optionsas map(*)
) as map(*)
Properties

This function is nondeterministic, context-dependent, and focus-independent.

Rules

This function loads an XSLT stylesheet and invokes it to perform a transformation.

The inputs to the transformation are supplied in the form of a map. The option parameter conventions apply to this map; they do not apply to any nested map unless otherwise specified.

The function first identifies the requested XSLT version, as follows:

  • If the xslt-version option is present, the requested XSLT version is the value of that option.

  • Otherwise, the requested XSLT version is the value of the [xsl:]version attribute of the outermost element in the supplied stylesheet or package.

The function then attempts to locate an XSLT processor that implements the requested XSLT version.

  • If a processor that implements the requested XSLT version is available, then it is used.

  • Otherwise, if a processor that implements a version later than the requested version is available, then it is used.

  • Otherwise, the function fails indicating that no suitable XSLT processor is available.

Note:

The phrase locate an XSLT processor includes the possibility of locating a software product and configuring it to act as an XSLT processor that implements the requested XSLT version.

If more than one XSLT processor is available under the above rules, then the one that is chosen may be selected according to the availability of requested features: see below.

Once an XSLT processor has been selected that implements a given version of XSLT, the processor follows the rules of that version of the XSLT specification. This includes any decision to operate in backwards or forwards compatibility mode. For example, if an XSLT 2.0 processor is selected, and the stylesheet specifies version="1.0", then the processor will operate in backwards compatibility mode; if the same processor is selected and the stylesheet specifies version="3.0", the processor will operate in forwards compatibility mode.

If the stylesheet to be executed is retrieved as an external resource, this is subject to the trust levelXP of the calling code. In addition, the ability of the loaded stylesheet to access additional resources is subject to the value of the supplied trusted option.

Note:

Versions of XSLT prior to 4.0 do not define any constraints on access to external resources. Many XSLT implementations, however, provide such mechanisms. An implementation of fn:transform that allows an XSLT processor to execute an untrustedXP stylesheet must ensure that the ability of that stylesheet to access resources is appropriately restricted, regardless of the version of XSLT.

The combinations of options that are relevant to each version of XSLT, other than xslt-version itself, are listed below. This is followed by a table giving the meaning of each option.

  1. For invocation of an XSLT 1.0 processor (see [XSL Transformations (XSLT) Version 1.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

    2. The source tree, provided as the value of the source-node option.

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      stylesheet-params (defaults to an empty map)
      initial-mode (defaults to the stylesheet’s default mode)
      delivery-format (defaults to document)
      serialization-params (defaults to an empty map)
      enable-messages (default is implementation-defined)
      requested-properties (default is an empty map)
      trusted (default is false)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

  2. For invocation of an XSLT 2.0 processor (see [XSL Transformations (XSLT) Version 2.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

    2. Invocation details, as exactly one of the following:

      1. For apply-templates invocation, all of the following:

        source-node

        Optionally, initial-mode (defaults to the stylesheet’s default mode)

      2. For call-template invocation, all of the following:

        initial-template

        Optionally, source-node

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      stylesheet-params (defaults to an empty map)
      base-output-uri (defaults to absent)
      delivery-format (defaults to document)
      serialization-params (defaults to an empty map)
      enable-messages (default is implementation-defined)
      enable-trace (default is implementation-defined)
      requested-properties (default is an empty map)
      trusted (default is false)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

  3. For invocation of an XSLT 3.0 or XSLT 4.0 processor (see [XSL Transformations (XSLT) Version 4.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided either by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

      Or by supplying exactly one of the following:

      package-location
      package-node
      package-text
      package-name plus optionally package-version

    2. Invocation details, as exactly one of the following combinations:

      1. For apply-templates invocation, all of the following:

        Exactly one of source-node, source-location, or initial-match-selection

        Optionally, initial-mode

        Optionally, template-params

        Optionally, tunnel-params

      2. For call-template invocation using an explicit template name, all of the following:

        initial-template

        Optionally, template-params

        Optionally, tunnel-params

        Optionally, source-node

      3. For call-template invocation using the defaulted template name xsl:initial-template, all of the following:

        Optionally, template-params

        Optionally, tunnel-params

        Note:

        If the source-node or source-locationoption is present and initial-template is absent, then apply-templates invocation will be used. To use call-template invocation on the template named xsl:initial-template while also supplying a context item for use when evaluating global variables, either (a) supply the context item using the global-context-item option, or (b) supply source-node, and set the initial-template option explicitly to the QName xsl:initial-template

      4. For call-function invocation, all of the following:

        initial-function

        function-params

      Note:

      The invocation method can be determined as the first of the following which applies:

      • If initial-function is present, then call-function invocation.

      • If initial-template is present, then call-template invocation.

      • If source-node or source-location or initial-match-selection is present, then apply-templates invocation.

      • Otherwise, call-template invocation using the default entry point xsl:initial-template.

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      static-params (defaults to an empty map)
      stylesheet-params (defaults to an empty map)
      global-context-item (defaults to absent)
      base-output-uri (defaults to absent)
      delivery-format
      serialization-params (defaults to an empty map)
      enable-assertions (default is false)
      enable-messages (default is implementation-defined)
      enable-trace (default is implementation-defined)
      requested-properties (default is an empty map)
      trusted (default is false)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

The meanings of each option are defined in the table below.

record(
base-output-uri?as xs:string,
cache?as xs:boolean,
delivery-format?as xs:string,
enable-assertions?as xs:boolean,
enable-messages?as xs:boolean,
enable-trace?as xs:boolean,
function-params?as array(item()*),
global-context-item?as item(),
initial-function?as xs:QName,
initial-match-selection?as item()*,
initial-mode?as xs:QName,
initial-template?as xs:QName,
package-name?as xs:string,
package-location?as xs:string,
package-node?as node(),
package-text?as xs:string,
package-version?as xs:string,
post-process?as fn(xs:string, item()*) as item()*,
requested-properties?as map(xs:QName, xs:anyAtomicType),
serialization-params?as map(xs:anyAtomicType, item()*),
source-location?as node(),
source-node?as node(),
static-params?as map(xs:QName, item()*),
stylesheet-base-uri?as xs:string,
stylesheet-location?as xs:string,
stylesheet-node?as node(),
stylesheet-params?as map(xs:QName, item()*),
stylesheet-text?as xs:string,
template-params?as map(xs:QName, item()*),
tunnel-params?as map(xs:QName, item()*),
trusted?as xs:boolean,
vendor-options?as { xs:QName, item()* },
xslt-version?as xs:decimal
)
KeyApplies toValueMeaning

base-output-uri?

1.0, 2.0, 3.0, 4.0The URI of the principal result document; also used as the base URI for resolving relative URIs of secondary result documents. If the value is a relative reference, it is resolved against the executable base URIXP of the fn:transform function call.
  • Type: xs:string

  • Default: The effect of not supplying a base output URI is defined by the XSLT specification; the implementation may supply a default, for example the current working directory. If the fn:transform function is called from XSLT, then the recommended default is the current output URI of the calling transformation.

cache?

1.0, 2.0, 3.0, 4.0This option has no effect on the result of the transformation but may affect efficiency. The value true indicates an expectation that the same stylesheet is likely to be used for more than one transformation; the value false indicates an expectation that the stylesheet will be used once only.
  • Type: xs:boolean

  • Default: true

delivery-format?

1.0, 2.0, 3.0, 4.0The manner in which the transformation results should be delivered. Applies both to the principal result document and to secondary result documents created using xsl:result-document.
  • Type: xs:string

  • Default: document

    If the relevant xsl:output or xsl:result-document element specifies build-tree="no" (applies to XSLT 3.0 only), then the default is raw.

documentThe result is delivered as a document node.
serializedThe result is delivered as a string, representing the results of serialization. Note that (as with the fn:serialize function) the final encoding stage of serialization (which turns a sequence of characters into a sequence of octets) is either skipped, or reversed by decoding the octet stream back into a character stream.
rawThe result of the initial template or function is returned as an arbitrary XDM value (after conversion to the declared type, but without wrapping in a document node, and without serialization): when this option is chosen, the returned map contains the raw result.
fileThe serialized result is written to persistent storage. This means that the fn:transform function has side-effects and becomes nondeterministic, so the option should be used with care, and the precise behavior may be implementation-defined. When this option is used, the URIs used for the base-output-uri and the URIs of any secondary result documents must be writable locations.

enable-assertions?

3.0, 4.0Indicates whether any xsl:assert instructions in the stylesheet are to be evaluated.
  • Type: xs:boolean

  • Default: false

enable-messages?

1.0, 2.0, 3.0, 4.0Indicates whether any xsl:message instructions in the stylesheet are to be evaluated. The destination and formatting of any such messages is implementation-defined.

enable-trace?

2.0, 3.0, 4.0Indicates whether any fn:trace functions in the stylesheet are to generate diagnostic messages. The destination and formatting of any such messages is implementation-defined.

function-params?

3.0, 4.0An array of values to be used as the arguments to the initial function call. The value is converted to the required type of the declared parameter using the function conversion rules.
  • Type: array(item()*)

  • Default: Empty array

global-context-item?

3.0, 4.0The value of the global context item, as defined in XSLT 3.0
  • Type: item()

  • Default: The value of source-node, if supplied

initial-function?

3.0, 4.0The name of the initial function to be called for call-function invocation. The arity of the function is inferred from the length of function-params.
  • Type: xs:QName

  • Default: n/a

initial-match-selection?

3.0, 4.0The value of the initial match selection, as defined in XSLT 3.0
  • Type: item()*

  • Default: The value of source-node

initial-mode?

1.0, 2.0, 3.0, 4.0The name of the initial processing mode.
  • Type: xs:QName

  • Default: none

initial-template?

2.0, 3.0, 4.0The name of a named template in the stylesheet to act as the initial entry point.
  • Type: xs:QName

  • Default: xsl:initial-template

package-name?

3.0, 4.0The name of the top-level stylesheet package to be invoked (an absolute URI)
  • Type: xs:string

  • Default: n/a

package-location?

3.0, 4.0The location of the top-level stylesheet package, as a relative or absolute URI
  • Type: xs:string

  • Default: n/a

package-node?

3.0, 4.0A document or element node containing the top-level stylesheet package
  • Type: node()

  • Default: n/a

package-text?

3.0, 4.0The top-level stylesheet package in the form of unparsed lexical XML.
  • Type: xs:string

  • Default: n/a

package-version?

3.0, 4.0The version of the top-level stylesheet package to be invoked.
  • Type: xs:string

  • Default: "*" (any version)

post-process?

1.0, 2.0, 3.0, 4.0A function that is used to post-process each result document of the transformation (both the principal result and secondary results), in whatever form it would otherwise be delivered (document, serialized, or raw). The first argument of the function is the key used to identify the result in the map return by the fn:transform function (for example, this will be the supplied base output URI in the case of the principal result, or the string “output” if no base output URI was supplied). The second argument is the actual value. The value that is returned in the result of the fn:transform function is the result of applying this post-processing.

Note:

If the implementation provides a way of writing or invoking functions with side-effects, this post-processing function might be used to save a copy of the result document to persistent storage. For example, if the implementation provides access to the EXPath File library [EXPath], then a serialized document might be written to filestore by calling the file:write function. Similar mechanisms might be used to issue an HTTP POST request that posts the result to an HTTP server, or to send the document to an email recipient. The semantics of calling functions with side-effects are entirely implementation-defined.

If the primary purpose of the post-processing function is achieved by means of such side-effects, and if the actual results are not needed by the caller of the fn:transform function, then it does not matter what the post-processing function actually returns (it could be an empty sequence, for example).

Calls to fn:transform can potentially have side-effects even in the absence of the post-processing option, because the XSLT specification allows a stylesheet to invoke extension functions that have side-effects. The semantics in this case are implementation-defined.

  • Type: fn(xs:string, item()*) as item()*

  • Default: fn($a, $b) { $b }

requested-properties?

1.0, 2.0, 3.0, 4.0The keys in the map are QNames that could legitimately be supplied in a call to the XSLT system-property function; the values in the map are the requested settings of the corresponding property. The boolean values true and false are equivalent to the string values yes and no. As a special case, setting a value for xsl:version has no effect, because of the potential for conflict with other options. For example:
  • Setting xsl:product-name to a particular value requests a particular XSLT software product.

  • Setting xsl:product-version requests a specific version of that product.

  • Setting xsl:is-schema-aware to true requests a schema-aware processor.

  • Setting xsl:xsd-version to "1.1" requests a processor that supports XML Schema version 1.1.

Setting a boolean property such as xsl:supports-dynamic-evaluation to false is interpreted as an explicit request for a processor in which the value of the property is false. The effect if the requests cannot be precisely met is implementation-defined. In some cases it may be appropriate to ignore the request or to provide an alternative (for example, a later version of the product than the one requested); in other cases it may be more appropriate to raise an error [err:FOXT0001] indicating that no suitable XSLT processor is available.
  • Type: map(xs:QName, xs:anyAtomicType)

  • Default: Empty map

serialization-params?

1.0, 2.0, 3.0, 4.0Serialization parameters for the principal result document. The supplied map follows the same rules that apply to a map supplied as the second argument of fn:serialize.
  • When a parameter is supplied, the corresponding value overrides or augments the value specified in the unnamed xsl:output declaration (or its default), following the same rules as when one xsl:output declaration overrides another with lower import precedence.

  • When a parameter is supplied and the corresponding value is an empty sequence (for example, { "standalone": () }), any value specified in the unnamed xsl:output declaration is overridden by the default value.

  • When a parameter is not supplied in serialization-params (that is, when the key is absent) the value that applies is the value appearing in the unnamed xsl:output declaration, or its default.

  • Type: map(xs:anyAtomicType, item()*)

  • Default: Empty map

source-location?

1.0, 2.0, 3.0, 4.0When source-location is supplied then it is expected to be an absolute or relative URI identifying an unparsed XML document. If relative, it is resolved against the static base URI of the fn:transform function call. The document at this location is parsed, and the document node acts as the initial-match-selection, that is, stylesheet execution starts by applying templates to this node. If the initial mode is streamable and a streaming XSLT 3.0 or XSLT 4.0 processor is used, then the supplied document is processed in streaming mode.
  • Type: node()

  • Default: n/a

source-node?

1.0, 2.0, 3.0, 4.0When source-node is supplied then the global-context-item (the context item for evaluating global variables) is the root of the tree containing the supplied node. In addition, for apply-templates invocation, the source-node acts as the initial-match-selection, that is, stylesheet execution starts by applying templates to this node.
  • Type: node()

  • Default: n/a

static-params?

3.0, 4.0The values of static parameters defined in the stylesheet; the keys are the names of the parameters, and the associated values are their values. The value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

stylesheet-base-uri?

1.0, 2.0, 3.0, 4.0A string intended to be used as the static base URI of the principal stylesheet module. This value must be used if no other static base URI is available. If the supplied stylesheet already has a base URI (which will generally be the case if the stylesheet is supplied using stylesheet-node or stylesheet-location) then it is implementation-defined whether this parameter has any effect. If the value is a relative reference, it is resolved against the executable base URIXP of the fn:transform function call.
  • Type: xs:string

  • Default: n/a

stylesheet-location?

1.0, 2.0, 3.0, 4.0URI that can be used to locate the principal stylesheet module. If relative, it is resolved against the executable base URIXP of the fn:transform function call. The value also acts as the default for stylesheet-base-uri.
  • Type: xs:string

  • Default: n/a

stylesheet-node?

1.0, 2.0, 3.0, 4.0Root of the tree containing the principal stylesheet module, as a document or element node. The base URI of the node acts as the default for stylesheet-base-uri.
  • Type: node()

  • Default: n/a

stylesheet-params?

1.0, 2.0, 3.0, 4.0A map holding values to be supplied for stylesheet parameters. The keys are the parameter names; the values are the corresponding parameter values. The values are converted if necessary to the required type using the coercion rules. The default is an empty map.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

stylesheet-text?

1.0, 2.0, 3.0, 4.0The principal stylesheet module in the form of unparsed lexical XML.
  • Type: xs:string

  • Default: n/a

template-params?

3.0, 4.0The values of non-tunnel parameters to be supplied to the initial template, used with both apply-templates and call-template invocation. Each value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: none

tunnel-params?

3.0, 4.0The values of tunnel parameters to be supplied to the initial template, used with both apply-templates and call-template invocation. Each value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

trusted?

Indicates whether the target stylesheet is trusted to access external resources. This applies both to resources statically referenced by the stylesheet (for example using xsl:include, xsl:import, xsl:use-package, or xsl:import-schema), and to resources accessed dynamically by executing the retrieved stylesheet, for example by use of the fn:doc or unparsed-text function.
  • Type: xs:boolean

  • Default: false()

trueThe loaded stylesheet has the same level of trust as the caller, and may therefore access all external resources available to the caller.
falseThe loaded stylesheet is untrustedXP, and is therefore unable to access external resources unless these have been made explicitly available by a trusted caller.

vendor-options?

1.0, 2.0, 3.0, 4.0Values for vendor-defined configuration options for the XSLT processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XSLT processor. The meaning of the associated value is implementation-defined. Implementations should ignore options whose names are in an unrecognized namespace. Default is an empty map.
  • Type: { xs:QName, item()* }

  • Default: Empty map

xslt-version?

1.0, 2.0, 3.0, 4.0The minimum level of the XSLT language that the processor must support.
  • Type: xs:decimal

  • Default: The [xsl:]version attribute at the outermost level of the stylesheet.

The result of the transformation is returned as a map. There is one entry in the map for the principal result document, and one for each secondary result document. The key is a URI in the form of an xs:string value. The key for the principal result document is the base output URI if specified, or the string "output" otherwise. The key for secondary result documents is the URI of the document, as an absolute URI. The associated value in each entry depends on the requested delivery format. If the delivery format is document, the value is a document node. If the delivery format is serialized, the value is a string containing the serialized result.

Where nodes are passed to or from the transformation, for example as the value of a stylesheet parameter or the result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XSLT implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotation, and about its relationships to other nodes passed across the interface.

It is implementation-defined whether the XSLT transformation is executed within the same execution scope as the calling code.

The function is nondeterministic in that it is implementation-dependent whether running the function twice against the same inputs produces identical results. The results of two invocations may differ in the identity of any returned nodes; they may also differ in other respects, for example because the value of fn:current-dateTime is different for the two invocations, or because the contents of external documents accessed using fn:doc or xsl:source-document change between one invocation and the next.

Error Conditions

A dynamic error is raised [err:FOXT0001] if the transformation cannot be invoked because no suitable XSLT processor is available. This includes (but is not limited to) the following cases:

  1. No XSLT processor is available;

  2. No XSLT processor supporting the requested version of XSLT is available;

  3. The XSLT processor API does not support some requested feature (for example, the ability to supply tunnel parameters externally);

A dynamic error is raised [err:FOXT0002] if an error is detected in the supplied parameters (for example if two mutually exclusive parameters are supplied).

If a static or dynamic error is reported by the XSLT processor, this function fails with a dynamic error, retaining the XSLT error code.

A dynamic error is raised [err:FOXT0003] if the XSLT transformation invoked by a call on fn:transform fails with a static or dynamic error, and no more specific error code is available.

Note:

XSLT 1.0 does not define any error codes, so this is the likely outcome with an XSLT 1.0 processor. XSLT 2.0 and 3.0 do define error codes, but some APIs do not expose them. If multiple errors are signaled by the transformation (which is most likely to happen with static errors) then the error code should where possible be that of one of these errors, chosen arbitrarily; the processor may make details of additional errors available to the application in an implementation-defined way.

A dynamic error is raised [err:FOXT0004] if the use of this function (or of selected options) has been externally disabled, for example for security reasons.

A dynamic error is raised [err:FOXT0006] if the transformation produces output containing characters available only in XML 1.1, and the calling processor cannot handle such characters.

Recursive use of the fn:transform function may lead to catastrophic failures such as non-termination or stack overflow. No error code is assigned to such conditions, since they cannot necessarily be detected by the processor.

Notes

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support a particular set of values for the xslt-version parameter.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality such as the ability to write to persistent resources.

Examples

The following example loads a stylesheet from the location render.xsl, applies it to a document loaded from test.xml, and uses an XPath expression to examine the result:

let $result := transform({
  "stylesheet-location": "render.xsl",
  "source-node": doc('test.xml')
})
return $result?output//body

18.419.4 fn:op

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 83 PR 173 11 October 2022]

Summary

Returns a function whose effect is to apply a supplied binary operator to two arguments.

Signature
fn:op(
$operatoras xs:string
) as fn(item()*, item()*) as item()*
Properties

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

Rules

The supplied operator must be one of:

",", "and", "or", "+", "-", "*", "div", "idiv", "mod", "=", "<", "<=", ">", ">=", "!=", "eq", "lt", "le", "gt", "ge", "ne", "<<", ">>", "precedes", "follows", "precedes-or-is", "follows-or-is", "is", "is-not", "||", "|", "union", "except", "intersect", "to", "otherwise".

The result of calling fn:op("⊙"), where is one of the above operators, is the function represented by the XPath expression:

fn($x, $y) { $x ⊙ $y }

For example, op("+") returns fn($x, $y) { $x + $y }.

Error Conditions

A type error is raised [err:XPTY0004]XP if the supplied argument is not one of the supported operators.

Notes

The function is useful in contexts where an arity-2 callback function needs to be supplied, and a standard operator meets the requirement.

For example, the XSLT xsl:map instruction has an on-duplicates attribute that expects such a function. Specifying on-duplicates="op(',')" is equivalent to specifying on-duplicates="fn($x, $y) { $x, $y }

The function is also useful in cases where the choice of operator to apply is made dynamically.

Some operators (such as and, or, and otherwise) have custom error handling semantics, with the effect that evaluating one of the operands cannot cause an error unless the other operand has a particular value (see [XML Path Language (XPath) 4.0] section 2.5.5 Guarded Expressions). Although implementations are free to make optimizations, it should be assumed that a function call such as op('and')(X, Y) will have the normal semantics of a dynamic function call, where the arguments are evaluated in any order, and a failure evaluating any argument may cause the function call as a whole to fail.

Examples
ExpressionResult
for-each-pair(21 to 25, 1 to 5, op("+"))

22, 24, 26, 28, 30

for-each-pair(21 to 25, 1 to 5, op("-"))

20, 20, 20, 20, 20

1920 Processing types

Changes in 4.0 (next | previous)

  1. New functions are provided to obtain information about built-in types and types defined in an imported schema.   [Issue 148 PR 1523 5 November 2024]

The functions in this section deliver information about schema types (including simple types and complex types). These may represent built-in types (such as xs:dateTime), user-defined types found in the static context (typically because they appear in an imported schema), or types used as type annotations on schema-validated nodes.

For more information on schema types, see 1.8.2 Schema Type Hierarchy. The properties of a schema type are described in terms of the properties of a Simple Type Definition or Complex Type Definition component as described in 3.16.1 The Simple Type Definition Schema Component XS11-1 and 3.4.1 The Complex Type Definition Schema Component XS11-1 respectively. Not all properties are exposed.

The structured representation of a schema type is described in 19.1.120.1.1 Record fn:schema-type-record.

Note:

Simple properties of a schema type that can be expressed as strings or booleans are represented in this record structure directly as atomic field values, while complex properties whose values are themselves types (for example, base-type and primitive-type) are represented as functions. This is done partly to make it easier for implementations to compute complex properties on demand rather than in advance, and partly to ensure that the overall structure is always acyclic. For example, the primitive type of xs:decimal is itself xs:decimal, and if this were represented as a field value without a guarding function, serialization of the map using the JSON output method would not terminate.

19.120.1 Functions returning type information

FunctionMeaning
fn:schema-typeReturns a record containing information about a named schema type in the static context.
fn:type-ofReturns information about the type of a value, as a string.
fn:atomic-type-annotationReturns a record containing information about the type annotation of an atomic value.
fn:node-type-annotationReturns a record containing information about the type annotation of an element or attribute node.

19.1.120.1.1 Record fn:schema-type-record

This record type represents the properties of a simple or complex type in a schema.

NameMeaning

name

The name of the type. Empty in the case of an anonymous type. Corresponds to {name}XS11-1 and {target namespace}XS11-1 in the XSD component model for simple and complex type components.

  • Type: xs:QName?

is-simple

True for a simple type, false for a complex type.

  • Type: xs:boolean

base-type

Function item returning the base type (the type from which this type is derived by restriction or extension). The function is always present, and returns an empty sequence in the case of the type xs:anyType. Corresponds to the {base type definition}XS11-1 property in the XSD component model.

  • Type: fn() as schema-type-record?

primitive-type?

For an atomic type, a function item returning the primitive type from which this type is ultimately derived. Corresponds to the {primitive type definition}XS11-1 in the XSD component model for simple types. Absent if the type is non atomic, or if it is the simple type xs:anyAtomicType. If this is a primitive type, the function item is idempotent.

  • Type: fn() as schema-type-record

variety?

For a simple type, one of "atomic", "list", or "union", corresponding to the {variety}XS11-1 of the simple type in the XSD component model. For a complex type, one of "empty", "simple", "element-only", or "mixed", corresponding to the {content type}XS11-1.{variety}XS11-1 of the complex type in the XSD component model. The value is absent in cases where the {variety}XS11-1 in the XSD component model is absent, for example for the type xs:anySimpleType.

  • Type: enum("atomic", "list", "union", "empty", "simple", "element-only", "mixed")

members?

For a simple type with variety "union", a function that returns a sequence of records representing the member types of the union, in order, corresponding to the {member type definitions}XS11-1 property in the XSD component model. For a simple type with variety "list", a function that returns a record representing the item type of the list type, corresponding to the {item type definition}XS11-1 property in the XSD component model. In all other cases, absent.

  • Type: fn() as schema-type-record*

simple-content-type?

For a complex type with variety "simple" (that is, a complex type with simple content), a function that returns a record representing the relevant simple type, corresponding to the {content type}XS11-1.{simple type definition}XS11-1 property in the XSD complex type component. In all other cases, absent.

  • Type: fn() as schema-type-record

matches?

For a generalized atomic typeXP, a function item that can be called to establish whether the supplied atomic item is an instance of this type. In all other cases, absent.

  • Type: fn(xs:anyAtomicType) as xs:boolean

constructor?

For a simple type, a function item that can be used to construct instances of this type. In the case of a named type that is present in the dynamic context, the result is the same function as returned by fn:function-lookup applied to the type name (with arity one). For details see 22.123.1 Constructor functions for XML Schema built-in atomic types and 22.523.5 Constructor functions for user-defined atomic and union types. Constructor function items are also available for anonymous types, and for types that might not be present in the dynamic context. The field is absent for complex types and for the abstract types xs:anyAtomicType, xs:anySimpleType, and xs:NOTATION. It is also absent for all namespace-sensitiveXP types.

  • Type: fn(xs:anyAtomicType?) as xs:anyAtomicType*

*

The record type is extensible (it may contain additional fields beyond those listed).

19.1.220.1.2 fn:schema-type

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 148 PR 1523 22 October 2024]

Summary

Returns a record containing information about a named schema type in the static context.

Signature
fn:schema-type(
$nameas xs:QName
) as schema-type-record?
Properties

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

Rules

If the static context (specifically, the in-scope schema typesXP) includes a schema type whose name matches $name, the function returns a schema-type-record containing information about that schema type. If not, it returns an empty sequence.

Examples
Expression:

schema-type( #xs:integer ) ? name

Result:

#xs:integer

Expression:

schema-type( #xs:long ) ? primitive-type() ? name

Result:

#xs:decimal

Expression:

schema-type( #xs:positiveInteger ) ? base-type() ? name

Result:

#xs:nonNegativeInteger

Expression:

schema-type( #xs:integer ) ? matches(23)

Result:

true()

Expression:

schema-type( #xs:numeric ) ? variety

Result:

"union"

Expression:

schema-type( #xs:numeric ) ? members() ? name

Result:

#xs:double, #xs:float, #xs:decimal

19.1.320.1.3 fn:type-of

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 1550 PR 1570 12 November 2024]

Summary

Returns information about the type of a value, as a string.

Signature
fn:type-of(
$valueas item()*
) as xs:string
Properties

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

Rules

The function returns a string, whose lexical form will always match the grammar of SequenceTypeXP, representing a sequence type that matches $value.

If $value is the empty sequence, the function returns the string "empty-sequence()".

Otherwise, the returned string is the concatenation of:

  1. A string representing the distinct item types that are present in $value, formed as follows:

    1. For each item in $value, construct a string representing its item type as described below.

    2. Eliminate duplicate strings from this list by applying the fn:distinct-values function, forming a sequence of strings $ss.

    3. If $ss contains only one string, use that string.

    4. Otherwise, return the result of the expression `({ fn:string-join($ss, "|") })`.

  2. An occurrence indicator: absent if $value contains exactly one item, or "+" if it contains more than one item.

The string representing the type of an individual item J is constructed as follows:

  1. If J is an XNodeDM, the result is one of the following strings, determined by the node kind of the node (see [XQuery and XPath Data Model (XDM) 4.0] section 7.6.9 node-kind Accessor):

    "document-node()"
    "element()"
    "attribute()"
    "text()"
    "processing-instruction()"
    "comment()"
    "namespace-node()"

  2. If J is a JNodeDM, the result is in the form jnode(T), where T is the result of applying the type-of function to the ·content· property of J.

  3. If J is an atomic item, the result is a string chosen as follows:

    1. Let T be the type denoted by the type annotation of J.

    2. If T is an anonymous type, set T to the base type of T, and repeat until a type is reached that is not anonymous.

    3. If the name of T is in the namespace http://www.w3.org/2001/XMLSchema, return the string "xs:local" where local is the local part of the name of T.

    4. Otherwise, return the name of T in the form of a URIQualifiedNameXP (that is, "Q{uri}local", or "Q{}local" if the name is in no namespace).

  4. If J is a function item:

    1. If J is an array, return "array(*)".

    2. If J is a map, return "map(*)".

    3. Otherwise, return "function(*)".

Error Conditions

If the $value argument is omitted and the context value is absentDM, the function raises type error [err:XPDY0002]XP.

Notes

In general, an item matches more than one type, and there are cases where there is no single matching type that is more specific than all the others. This is especially true with functions, maps, and arrays. This function therefore selects one of the types that matches the item, which is not necessarily the most specific type.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

Examples
Variables
let $e := <doc>
  <p id="alpha" xml:id="beta">One</p>
  <p id="gamma" xmlns="http://example.com/ns">Two</p>
  <ex:p id="delta" xmlns:ex="http://example.com/ns">Three</ex:p>
  <?pi 3.14159?>
</doc>
ExpressionResult
type-of($e//*[@id = 'alpha'])

"element()"

type-of($e//*)

"element()+"

type-of($e//@id[. = 'gamma'])

"attribute()"

type-of($e//node()[. = '3.14159'])

"processing-instruction()"

type-of($e//no-such-node)

"empty-sequence()"

type-of($e/child::node())

"(element()|processing-instruction())+"

type-of(1)

"xs:integer"

type-of(1 to 5)

"xs:integer+"

type-of((1, 1.2, 2))

"(xs:integer|xs:decimal)+"

type-of([ 1, 2, 3 ])

"array(*)"

type-of({ 'a': 1 })

"map(*)"

type-of(type-of#1)

"function(*)"

type-of(jtree([]))

"jnode(array(*))"

19.1.420.1.4 fn:atomic-type-annotation

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 148 PR 1523 22 October 2024]

Summary

Returns a record containing information about the type annotation of an atomic value.

Signature
fn:atomic-type-annotation(
$valueas xs:anyAtomicType
) as schema-type-record
Properties

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

Rules

Given an atomic value, the function returns a schema-type-record containing information about the atomic type represented by its type annotationDM.

Notes

The result will always have ?is-simple = true() and ?variety = "atomic". In a non-schema-aware environment the type will always be a built-in atomic type in the xs namespace: see 1.8.3 Atomic Type Hierarchy. Where a schema is in use, however, the result may be an atomic type defined in the schema, which may be an anonymous type.

Note that under the function coercion rules, it is possible to supply a node as the argument, which will then be atomized. In simple cases the type annotation on the atomized value will be the same as the type annotation on the node. But this is not always true: for example the type annotation on the node might be a complex type with simple content, while the type annotation on its atomized value is the corresponding simple content type. To get the type annotation on the node, use the function fn:node-type-annotation.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

Examples
Expression:
atomic-type-annotation(23) ? name
Result:
#xs:integer
Expression:
let $x := 23, $y := 93.7 
return atomic-type-annotation($x) ? matches($y)
Result:
false()
Expression:
atomic-type-annotation(xs:numeric('23.2')) ? name
Result:
#xs:double

19.1.520.1.5 fn:node-type-annotation

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 148 PR 1523 22 October 2024]

Summary

Returns a record containing information about the type annotation of an element or attribute node.

Signature
fn:node-type-annotation(
$nodeas (element() | attribute())
) as schema-type-record
Properties

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

Rules

Given an element or attribute node, the function returns a schema-type-record containing information about the schema type represented by its type annotationDM.

Notes

For an element that has not been schema-validated, the type annotation is always xs:untyped.

For an attribute that has not been schema-validated, the type annotation is always xs:untypedAtomic.

The type annotation of an attribute node is always a simple type; the type annotation of an element node may be simple or complex.

Examples
Expression:
let $e := parse-xml("<e/>")/*
return node-type-annotation($e) ? name
Result:
#xs:untyped
Expression:
let $a := parse-xml("<e a='3'/>")//@a
return node-type-annotation($a) ? name
Result:
#xs:untypedAtomic
Expression:
let $x := json-to-xml('[23, 24]', { 'validate': true() })
return node-type-annotation($x/*) ? name
Result:
#fn:arrayType
Expression:
let $x := json-to-xml('[23, 24]', { 'validate': true() })
let $n23 := $x//fn:number[. = 23]                  
let $type := node-type-annotation($n23)
return ($type ? name, 
        $type ? base-type() ? name, 
        $type ? base-type() ? base-type() ? name)
Result:
#fn:numberType, 
#fn:finiteNumberType, 
#xs:double

2021 Accessing the context

The following functions are defined to obtain information from the static or dynamic context.

FunctionMeaning
fn:current-dateReturns the current date.
fn:current-dateTimeReturns the current date and time (with timezone).
fn:current-timeReturns the current time.
fn:default-collationReturns the value of the default collation property from the dynamic context.
fn:default-languageReturns the value of the default language property from the dynamic context.
fn:implicit-timezoneReturns the value of the implicit timezone property from the dynamic context.
fn:lastReturns the context size from the dynamic context.
fn:positionReturns the context position from the dynamic context.
fn:static-base-uriThis function returns the value of the executable base URI property from the dynamic context.

20.121.1 fn:current-date

Summary

Returns the current date.

Signature
fn:current-date() as xs:date
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns xs:date(fn:current-dateTime()). This is an xs:date (with timezone) that is current at some time during the evaluation of a query or transformation in which fn:current-date is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-date is implementation-dependent.

Notes

The returned date will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples

current-date() returns an xs:date corresponding to the current date. For example, a call of current-date() might return 2004-05-12+01:00.

20.221.2 fn:current-dateTime

Summary

Returns the current date and time (with timezone).

Signature
fn:current-dateTime() as xs:dateTimeStamp
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns the current dateTime (with timezone) from the dynamic context. (See [XML Path Language (XPath) 4.0] section B.2 Dynamic Context Components.) This is an xs:dateTime that is current at some time during the evaluation of a query or transformation in which fn:current-dateTime is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-dateTime() is implementation-dependent.

If the implementation supports data types from XSD 1.1 then the returned value will be an instance of xs:dateTimeStamp. Otherwise, the only guarantees are that it will be an instance of xs:dateTime and will have a timezone component.

Notes

The returned xs:dateTime will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples

current-dateTime() returns an xs:dateTimeStamp corresponding to the current date and time. For example, a call of current-dateTime() might return 2004-05-12T18:17:15.125Z corresponding to the current time on May 12, 2004 in timezone Z.

20.321.3 fn:current-time

Summary

Returns the current time.

Signature
fn:current-time() as xs:time
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns xs:time(fn:current-dateTime()). This is an xs:time (with timezone) that is current at some time during the evaluation of a query or transformation in which fn:current-time is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-time() is implementation-dependent.

Notes

The returned time will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples

current-time() returns an xs:time corresponding to the current time. For example, a call of current-time() might return 23:17:00.000-05:00.

20.421.4 fn:default-collation

Summary

Returns the value of the default collation property from the dynamic context.

Signature
fn:default-collation() as xs:string
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

Returns the value of the default collation property from the dynamic context context. Components of the dynamic context are described in [XML Path Language (XPath) 4.0] section 2.2.2 Dynamic Context.

Notes

The default collation property can never be absent. If it is not explicitly defined, a system defined default can be invoked. If this is not provided, the Unicode codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint) is used.

In most cases, the default collation is known statically, and a call on this function can therefore be pre-evaluated during static analysis. The only notable exception is when a call on default-collation() is used to define the default value of a parameter to a user-defined function. In this case it is interpreted as a reference to the default collation in the context of the relevant function call, which may differ from the default collation of the function definition.

20.521.5 fn:default-language

Summary

Returns the value of the default language property from the dynamic context.

Signature
fn:default-language() as xs:language
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on default language.

Rules

Returns the value of the default language property from the dynamic context. Components of the dynamic context are described in [XML Path Language (XPath) 4.0] section 2.2.2 Dynamic Context.

Notes

The default language property can never be absent. The functions fn:format-integer, fn:format-date, fn:format-time, and fn:format-dateTime are defined to use the default language if no explicit language is supplied. The default language may play a role in selection of a default collation, but this is not a requirement.

20.621.6 fn:implicit-timezone

Summary

Returns the value of the implicit timezone property from the dynamic context.

Signature
fn:implicit-timezone() as xs:dayTimeDuration
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns the value of the implicit timezone property from the dynamic context. Components of the dynamic context are described in [XML Path Language (XPath) 4.0] section B.2 Dynamic Context Components.

20.721.7 fn:last

Summary

Returns the context size from the dynamic context.

Signature
fn:last() as xs:integer
Properties

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

Rules

Returns the context size from the dynamic context. (See [XML Path Language (XPath) 4.0] section B.2 Dynamic Context Components.)

Error Conditions

A type error is raised [err:XPDY0002]XP if the context size is absentDM.

Notes

Under most circumstances, the context size is absent only if the context value is absent. However, XSLT 3.0 with streaming defines situations in which the context value and context position are known, but the context size is unknown.

Examples
ExpressionResult
(1 to 20)[last() - 1]

19

20.821.8 fn:position

Summary

Returns the context position from the dynamic context.

Signature
fn:position() as xs:integer
Properties

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

Rules

Returns the context position from the dynamic context. (See [XML Path Language (XPath) 4.0] section B.2 Dynamic Context Components.)

Error Conditions

A type error is raised [err:XPDY0002]XP if the context value is absentDM.

20.921.9 fn:static-base-uri

Summary

This function returns the value of the executable base URI property from the dynamic context.

Signature
fn:static-base-uri() as xs:anyURI?
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on executable base URI.

Rules

The function (despite its name) returns the value of the executable base URI property from the dynamic context. If the property is absent, the empty sequence is returned.

Components of the dynamic context are described in [XML Path Language (XPath) 4.0] section 2.2.2 Dynamic Context .

Notes

The executable base URI will in many cases be the same as the static base URI in the static context. However, XQuery and XSLT give an implementation freedom to use different base URIs during the static analysis phase and the dynamic evaluation phase, that is, for retrieval of compile-time and run-time resources respectively. This is appropriate when the implementation allows the output of static analysis (a “compiled” query or stylesheet) to be deployed for execution to a different location from the one where static analysis took place. In this situation, the fn:static-base-uri function should return a URI suitable for locating resources needed during dynamic evaluation.

If a call on the fn:static-base-uri function appears within the expression used to define the value of an optional parameter to a user-defined function, then the value supplied to the function (if the argument is omitted) will be the executable base URI from the dynamic context of the function caller. This allows such a function to resolve relative URIs supplied in other parameters to the same function.

2122 Errors and diagnostics

21.122.1 Raising errors

In this document, as well as in [XQuery 4.0: An XML Query Language] and [XML Path Language (XPath) 4.0], the phrase “an error is raised” is used. Raising an error is equivalent to calling the fn:error function defined in this section with the provided error code. Except where otherwise specified, errors defined in this specification are dynamic errors. Some errors, however, are classified as type errors. Type errors are typically used where the presence of the error can be inferred from knowledge of the type of the actual arguments to a function, for example with a call such as fn:string(fn:abs#1). Host languages may allow type errors to be reported statically if they are discovered during static analysis.

When function specifications indicate that an error is to be raised, the notation “[error code ]” is used to specify an error code. Each error defined in this document is identified by an xs:QName that is in the http://www.w3.org/2005/xqt-errors namespace, represented in this document by the err prefix. It is this xs:QName that is actually passed as an argument to the fn:error function. Calling this function raises an error. For a more detailed treatment of error handing, see 2.3.3 Handling Dynamic Errors XP31.

The fn:error function is a general function that may be called as above but may also be called from [XQuery 4.0: An XML Query Language] or [XML Path Language (XPath) 4.0] applications with, for example, an xs:QName argument.

21.1.122.1.1 fn:error

Changes in 4.0 (next | previous)

  1. All three arguments are now optional, and each argument can be set to an empty sequence. Previously if $description was supplied, it could not be empty.  [Issue 895 PR 901 16 December 2023]

Summary

Calling the fn:error function raises an application-defined error.

Signature
fn:error(
$codeas xs:QName?:= (),
$descriptionas xs:string?:= (),
$valueas item()*:= .
) as item()*
Properties

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

Rules

This function never returns a value. Instead it always raises an error. The effect of the error is identical to the effect of dynamic errors raised implicitly, for example when an incorrect argument is supplied to a function.

The parameters to the fn:error function supply information that is associated with the error condition and that is made available to a caller that asks for information about the error. The error may be caught either by the host language (using a try/catch construct in XSLT or XQuery, for example), or by the calling application or external processing environment. The way in which error information is returned to the external processing environment is implementation-dependent.

There are three pieces of information that may be associated with an error.

  • The $code is an error code that distinguishes this error from others. It is an xs:QName; the namespace URI conventionally identifies the component, subsystem, or authority responsible for defining the meaning of the error code, while the local part identifies the specific error condition. The namespace URI http://www.w3.org/2005/xqt-errors is used for errors defined in this specification; other namespace URIs may be used for errors defined by the application.

    If the external processing environment expects the error code to be returned as a URI or a string rather than as an xs:QName, then an error code with namespace URI NS and local part LP will be returned in the form NS#LP. The namespace URI part of the error code should therefore not include a fragment identifier.

    If no value is supplied for the $code argument, or if the value supplied is an empty sequence, the effective value of the error code is fn:QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000').

  • The $description is a natural-language description of the error condition.

    If no value is supplied for the $description argument, or if the value supplied is an empty sequence, then the effective value of the description is implementation-dependent.

  • The $value is an arbitrary value used to convey additional information about the error, and may be used in any way the application chooses.

    If no value is supplied for the $value argument or if the value supplied is an empty sequence, then the effective value of the error object is implementation-dependent.

Error Conditions

This function always raises a dynamic error. By default, it raises [err:FOER0000]

Notes

The value of the $description parameter may need to be localized.

Since the function never returns a value, the declared return type of item()* is a convenient fiction. It is relevant insofar as a function item such as error#1 may (as a consequence of function coercion) be supplied in contexts where a function with a more specific return type is required.

Any QName may be used as an error code; there are no reserved names or namespaces. The error is always classified as a dynamic error, even if the error code used is one that is normally used for static errors or type errors.

Examples
Expression:

error()

Result:

Raises error FOER0000.

(This returns the URI http://www.w3.org/2005/xqt-errors#FOER0000 (or the corresponding xs:QName) to the external processing environment, unless the error is caught using a try/catch construct in the host language.)

Expression:
error(
  QName('http://www.example.com/HR', 'myerr:toohighsal'),
  'Salary is too high'
)
Result:

Raises error myerr:toohighsal.

(This returns http://www.example.com/HR#toohighsal and the xs:string"Salary is too high" (or the corresponding xs:QName) to the external processing environment, unless the error is caught using a try/catch construct in the host language.)

21.222.2 Diagnostic tracing

21.2.122.2.1 fn:trace

Changes in 4.0 (next | previous)

  1. The $label argument can now be set to an empty sequence. Previously if $label was supplied, it could not be empty.  [Issue 895 PR 901 16 December 2023]

Summary

Provides an execution trace intended to be used in debugging queries.

Signature
fn:trace(
$inputas item()*,
$labelas xs:string?:= ()
) as item()*
Properties

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

Rules

The function returns $input, unchanged.

In addition, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination.

Any serialization of the implementation’s trace output must not raise an error. This can be achieved (for example) by using a serialization method that can handle arbitrary input, such as the adaptive output method (see 10 Adaptive Output Method SER31).

The format of the trace output and its order are implementation-dependent. Therefore, the order in which the output appears is not predictable. This also means that if dynamic errors occur (whether or not they are caught using try/catch), it may be unpredictable whether any output is reported before the error occurs.

Notes

If the trace information is unrelated to a specific value, fn:message can be used instead.

Examples

Consider a situation in which a user wants to investigate the actual value passed to a function. Assume that in a particular execution, $v is an xs:decimal with value 124.84. Writing fn:trace($v, 'the value of $v is:') will return $v. The processor may output "124.84" and "the value of $v is:" to an implementation-defined destination.

The following two XPath expressions are identical, but only the second provides trace feedback to the user:

  • //book[xs:decimal(@price) gt 100]

  • //book[xs:decimal(@price) gt 100] => trace('books more expensive than €100:')

21.2.222.2.2 fn:message

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issues 574 651 PRs 629 803 7 November 2023]

Summary

Outputs trace information and discards the result.

Signature
fn:message(
$inputas item()*,
$labelas xs:string?:= ()
) as empty-sequence()
Properties

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

Rules

Similar to fn:trace, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination.

In contrast to fn:trace, the function returns an empty sequence.

Any serialization of the implementation’s log output must not raise an error. This can e.g. be achieved by using a serialization method that can handle arbitrary input, such as the 10 Adaptive Output Method SER31.

The format of the log output and its order are implementation-dependent. Therefore, the order in which the output appears is not predictable. This also means that if dynamic errors occur (whether or not they are caught using try/catch), it may be unpredictable whether any output is logged before the error occurs.

Notes

The function can be used for debugging. It can also be helpful in productive environments, e.g. to store dynamic input and evaluations to log files.

Examples

The following two XPath expressions are identical, but only the second logs any feedback:

  • //book[xs:decimal(@price) lt 1000]

  • //book[if (xs:decimal(@price) lt 1000) then true() else message(@price, @title || ' is unexpectedly expensive: ')]

2223 Constructor functions

Changes in 4.0 (next | previous)

  1. Constructor functions now have a zero-arity form; the first argument defaults to the context item.   [Issue 658 PR 662 29 August 2023]

Constructor functions are used to convert a supplied value to a given type, and the name of the function is the same as the name of the target type. This section describes constructor functions corresponding to the following types:

Constructor functions are defined for all user-defined named simple types, and for most built-in atomic, list, and union types. The only named simple types that have no constructor function are those that have no instances other than instances of their derived types: specifically, xs:anySimpleType, xs:anyAtomicType, and xs:NOTATION.

22.123.1 Constructor functions for XML Schema built-in atomic types

Every built-in atomic type that is defined in [XML Schema Part 2: Datatypes Second Edition], except xs:anyAtomicType and xs:NOTATION, has an associated constructor function. The type xs:untypedAtomic, defined in 2.7 Schema Information DM31 and the two derived types xs:yearMonthDuration and xs:dayTimeDuration defined in 2.7 Schema Information DM31 also have associated constructor functions. Implementations may additionally provide a constructor functions for the new datatype xs:dateTimeStamp introduced in [XSD 1.1 Part 2].

A constructor function is not defined for xs:anyAtomicType as there are no atomic items with type annotation xs:anyAtomicType at runtime, although this can be a statically inferred type. A constructor function is not defined for xs:NOTATION since it is defined as an abstract type in [XML Schema Part 2: Datatypes Second Edition]. If the static context (See 2.1.1 Static Context XP31) contains a type derived from xs:NOTATION then a constructor function is defined for it. See 22.523.5 Constructor functions for user-defined atomic and union types.

The form of the constructor function for an atomic type eg:TYPE is:

eg:TYPE(
$valueas xs:anyAtomicType?:= .
) as eg:TYPE?

If $arg is the empty sequence, the empty sequence is returned. For example, the signature of the constructor function corresponding to the xs:unsignedInt type defined in [XML Schema Part 2: Datatypes Second Edition] is:

xs:unsignedInt(
$argas xs:anyAtomicType?:= .
) as xs:unsignedInt?

Calling the constructor function xs:unsignedInt(12) returns the xs:unsignedInt value 12. Another call of that constructor function that returns the same xs:unsignedInt value is xs:unsignedInt("12"). The same result would also be returned if the constructor function were to be called with a node that had a typed value equal to the xs:unsignedInt 12. The standard features described in 2.4.2 Atomization XP31 would atomize the node to extract its typed value and then call the constructor with that value. If the value passed to a constructor is not in the lexical space of the datatype to be constructed, and cannot be converted to a value in the value space of the datatype under the rules in this specification, then an dynamic error is raised [err:FORG0001].

The semantics of the constructor function xs:TYPE(arg) are identical to the semantics of arg cast as xs:TYPE? . See 2324 Casting.

If the argument to a constructor function is a literal, the result of the function may be evaluated statically; if an error is found during such evaluation, it may be reported as a static error.

Special rules apply to constructor functions for xs:QName and types derived from xs:QName and xs:NOTATION. See 22.223.2 Constructor functions for xs:QName and xs:NOTATION.

The argument is optional, and defaults to the context value (which will be atomized if necessary).

The following constructor functions for the built-in atomic types are supported:

  • xs:string(
    $valueas xs:anyAtomicType?:= .
    ) as xs:string?
  • xs:boolean(
    $valueas xs:anyAtomicType?:= .
    ) as xs:boolean?
  • xs:decimal(
    $valueas xs:anyAtomicType?:= .
    ) as xs:decimal?
  • xs:float(
    $valueas xs:anyAtomicType?:= .
    ) as xs:float?

    Implementations should return negative zero for xs:float("-0.0E0"). But because [XML Schema Part 2: Datatypes Second Edition] does not distinguish between the values positive zero and negative zero, implementations may return positive zero in this case.

  • xs:double(
    $valueas xs:anyAtomicType?:= .
    ) as xs:double?

    Implementations should return negative zero for xs:double("-0.0E0"). But because [XML Schema Part 2: Datatypes Second Edition] does not distinguish between the values positive zero and negative zero, implementations may return positive zero in this case.

  • xs:duration(
    $valueas xs:anyAtomicType?:= .
    ) as xs:duration?
  • xs:dateTime(
    $valueas xs:anyAtomicType?:= .
    ) as xs:dateTime?
  • xs:time(
    $valueas xs:anyAtomicType?:= .
    ) as xs:time?
  • xs:date(
    $valueas xs:anyAtomicType?:= .
    ) as xs:date?
  • xs:gYearMonth(
    $valueas xs:anyAtomicType?:= .
    ) as xs:gYearMonth?
  • xs:gYear(
    $valueas xs:anyAtomicType?:= .
    ) as xs:gYear?
  • xs:gMonthDay(
    $valueas xs:anyAtomicType?:= .
    ) as xs:gMonthDay?
  • xs:gDay(
    $valueas xs:anyAtomicType?:= .
    ) as xs:gDay?
  • xs:gMonth(
    $valueas xs:anyAtomicType?:= .
    ) as xs:gMonth?
  • xs:hexBinary(
    $valueas xs:anyAtomicType?:= .
    ) as xs:hexBinary?
  • xs:base64Binary(
    $valueas xs:anyAtomicType?:= .
    ) as xs:base64Binary?
  • xs:anyURI(
    $valueas xs:anyAtomicType?:= .
    ) as xs:anyURI?
  • xs:QName(
    $valueas xs:anyAtomicType?:= .
    ) as xs:QName?

    See 22.223.2 Constructor functions for xs:QName and xs:NOTATION for special rules.

  • xs:normalizedString(
    $valueas xs:anyAtomicType?:= .
    ) as xs:normalizedString?
  • xs:token(
    $valueas xs:anyAtomicType?:= .
    ) as xs:token?
  • xs:language(
    $valueas xs:anyAtomicType?:= .
    ) as xs:language?
  • xs:NMTOKEN(
    $valueas xs:anyAtomicType?:= .
    ) as xs:NMTOKEN?
  • xs:Name(
    $valueas xs:anyAtomicType?:= .
    ) as xs:Name?
  • xs:NCName(
    $valueas xs:anyAtomicType?:= .
    ) as xs:NCName?
  • xs:ID(
    $valueas xs:anyAtomicType?:= .
    ) as xs:ID?
  • xs:IDREF(
    $valueas xs:anyAtomicType?:= .
    ) as xs:IDREF?
  • xs:ENTITY(
    $valueas xs:anyAtomicType?:= .
    ) as xs:ENTITY?

    See 23.1.1024.1.10 Casting to xs:ENTITY for rules related to constructing values of type xs:ENTITY and types derived from it.

  • xs:integer(
    $valueas xs:anyAtomicType?:= .
    ) as xs:integer?
  • xs:nonPositiveInteger(
    $valueas xs:anyAtomicType?:= .
    ) as xs:nonPositiveInteger?
  • xs:negativeInteger(
    $valueas xs:anyAtomicType?:= .
    ) as xs:negativeInteger?
  • xs:long(
    $valueas xs:anyAtomicType?:= .
    ) as xs:long?
  • xs:int(
    $valueas xs:anyAtomicType?:= .
    ) as xs:int?
  • xs:short(
    $valueas xs:anyAtomicType?:= .
    ) as xs:short?
  • xs:byte(
    $valueas xs:anyAtomicType?:= .
    ) as xs:byte?
  • xs:nonNegativeInteger(
    $valueas xs:anyAtomicType?:= .
    ) as xs:nonNegativeInteger?
  • xs:unsignedLong(
    $valueas xs:anyAtomicType?:= .
    ) as xs:unsignedLong?
  • xs:unsignedInt(
    $valueas xs:anyAtomicType?:= .
    ) as xs:unsignedInt?
  • xs:unsignedShort(
    $valueas xs:anyAtomicType?:= .
    ) as xs:unsignedShort?
  • xs:unsignedByte(
    $valueas xs:anyAtomicType?:= .
    ) as xs:unsignedByte?
  • xs:positiveInteger(
    $valueas xs:anyAtomicType?:= .
    ) as xs:positiveInteger?
  • xs:yearMonthDuration(
    $valueas xs:anyAtomicType?:= .
    ) as xs:yearMonthDuration?
  • xs:dayTimeDuration(
    $valueas xs:anyAtomicType?:= .
    ) as xs:dayTimeDuration?
  • xs:untypedAtomic(
    $valueas xs:anyAtomicType?:= .
    ) as xs:untypedAtomic?
  • xs:dateTimeStamp(
    $valueas xs:anyAtomicType?:= .
    ) as xs:dateTimeStamp?

    Available only if the implementation supports XSD 1.1.

22.223.2 Constructor functions for xs:QName and xs:NOTATION

Special rules apply to constructor functions for the types xs:QName and xs:NOTATION, for two reasons:

  • Values cannot belong directly to the type xs:NOTATION, only to its subtypes.

  • The lexical representation of these types uses namespace prefixes, whose meaning is context-dependent.

These constraints result in the following rules:

  1. There is no constructor function for xs:NOTATION. Constructors are defined, however, for xs:QName, for types derived or constructed from xs:QName, and for types derived or constructed from xs:NOTATION.

  2. When converting from an xs:string, the prefix within the lexical xs:QName supplied as the argument is resolved to a namespace URI using the statically known namespaces from the static context. If the lexical xs:QName has no prefix, the namespace URI of the resulting expanded-QName is the default namespace for elements and types, taken from the static context. Components of the static context are defined in 2.1.1 Static Context XP31. A dynamic error is raised [err:FONS0004] if the prefix is not bound in the static context. As described in 2.1 Terminology DM31, the supplied prefix is retained as part of the expanded-QName value.

When a constructor function for a namespace-sensitive type is used as a literal function item or in a partial function application (for example, xs:QName#1 or xs:QName(?)) the namespace bindings that are relevant are those from the static context of the literal function item or partial function application. When a constructor function for a namespace-sensitive type is obtained by means of the fn:function-lookup function, the relevant namespace bindings are those from the static context of the call on fn:function-lookup.

Note:

When the supplied argument to the xs:QName constructor function is a node, the node is atomized in the usual way, and if the result is xs:untypedAtomic it is then converted as if a string had been supplied. The effect might not be what is desired. For example, given the attribute xsi:type="my:type", the expression xs:QName(@xsi:type) might fail on the grounds that the prefix my is undeclared. This is because the namespace bindings are taken from the static context (that is, from the query or stylesheet), and not from the source document containing the @xsi:type attribute. The solution to this problem is to use the function call resolve-QName(@xsi:type, .) instead.

22.323.3 Constructor functions for XML Schema built-in list types

Each of the three built-in list types defined in [XML Schema Part 2: Datatypes Second Edition], namely xs:NMTOKENS, xs:ENTITIES, and xs:IDREFS, has an associated constructor function.

The function signatures are as follows:

  • xs:NMTOKENS(
    $valueas xs:string?:= .
    ) as xs:NMTOKEN*
  • xs:ENTITIES(
    $valueas xs:string?:= .
    ) as xs:ENTITY*
  • xs:IDREFS(
    $valueas xs:string?:= .
    ) as xs:IDREF*

The semantics are equivalent to casting to the corresponding types from xs:string.

All three of these types have the facet minLength = 1 meaning that there must always be at least one item in the list. The return type, however, allows for the fact that when the argument to the function is an empty sequence, the result is an empty sequence.

Note:

In the case of atomic types, it is possible to use an expression such as xs:date(@date-of-birth) to convert an attribute value to an instance of xs:date, knowing that this will work both in the case where the attribute is already annotated as xs:date, and also in the case where it is xs:untypedAtomic. This approach does not work with list types, because it is not permitted to use a value of type xs:NMTOKEN* as input to the constructor function xs:NMTOKENS. Instead, it is necessary to use conditional logic that performs the conversion only in the case where the input is untyped: if (@x instance of attribute(*, xs:untypedAtomic)) then xs:NMTOKENS(@x) else data(@x)

22.423.4 Constructor functions for XML Schema built-in union types

There is a constructor function for the union type xs:numeric defined in [XQuery and XPath Data Model (XDM) 4.0]. The function signature is:

  • xs:numeric(
    $valueas xs:anyAtomicType?:= .
    ) as xs:numeric?

The semantics are determined by the rules in 23.3.724.3.7 Casting to union types. These rules have the effect that:

  1. If the argument is an instance of xs:double, xs:float, or xs:decimal, then the result is an instance of the same primitive type, with the same value;

  2. If the argument is an instance of xs:boolean, the result is the xs:double value 0.0e0 or 1.0e0;

  3. If the argument is an instance of xs:string or xs:untypedAtomic, then:

    1. If the value is in the lexical space of xs:double, the result will be the corresponding xs:double value;

    2. Otherwise, a dynamic error [err:FORG0001] occurs;

    Note:

    The result will never be an instance of xs:float, xs:decimal, or xs:integer. This is because xs:double appears first in the list of member types of xs:numeric, and its lexical space subsumes the lexical space of the other numeric types. Thus, unlike XPath numeric literals, the result does not depend on the lexical form of the supplied value. The reason for this design choice is to retain compatibility with the function conversion rules: functions such as fn:abs and fn:round are declared to expect an instance of xs:numeric as their first or only argument, and compatibility with the function conversion rules defined in earlier versions of these specifications demands that when an untyped atomic item (or untyped node) is supplied as the argument, it is converted to an xs:double value even if its lexical form is that (say) of an integer.

  4. In all other cases, a dynamic error [err:FORG0001] occurs.

In the case of an implementation that supports XSD 1.1, there is a constructor function associated with the built-in union type xs:error.

The function signature is as follows:

  • xs:error(
    $valueas xs:anyAtomicType?:= .
    ) as xs:error?

The semantics are equivalent to casting to the corresponding union type (see 23.3.724.3.7 Casting to union types).

Note:

Because xs:error has no member types, and therefore has an empty value space, casting will always fail with a dynamic error except in the case where the supplied argument is an empty sequence, in which case the result is also an empty sequence.

22.523.5 Constructor functions for user-defined atomic and union types

For every named user-defined simple type in the static context (See 2.1.1 Static Context XP31), there is a constructor function whose name is the same as the name of the type.

For named atomic types, the rules are the same as the rules for constructing built-in derived atomic types defined in 22.123.1 Constructor functions for XML Schema built-in atomic types. For a named atomic type T, the signature of the function takes the form T($value as xs:anyAtomicType? := .) as T?, and the semantics are the same as casting to derived types: see 23.3.124.3.1 Casting to derived types..

For named union types, the rules follow the same principles as the rules for constructing built-in union types defined in 22.423.4 Constructor functions for XML Schema built-in union types. For a named union type U, the signature of the function takes the form U($value as xs:anyAtomicType? := .) as U?, and the semantics are the same as casting to union types: see 23.3.724.3.7 Casting to union types.

For named list types, the rules follow the same principles as the rules for constructing built-in list types defined in 22.323.3 Constructor functions for XML Schema built-in list types. For a named list type L, where the item type of L is I, the signature of the function takes the form L($value as xs:string? := .) as I*, and the semantics are the same as casting to list types: see 23.3.824.3.8 Casting to list types.

Constructor functions are available both for named types defined in an imported schema (that is, named simple types in the in-scope schema typesXP), and for types defined by means of named item typesXP. Specifically, named enumeration types follow the same rules as schema types derived by restricting xs:string, and named local union types follow the same rules as union types defined in a schema.

Special rules apply to constructor functions for namespace-sensitive types, that is, atomic types derived from xs:QName and xs:NOTATION, list types that have a namespace-sensitive item type, and union types that have a namespace-sensitive member type. See 22.223.2 Constructor functions for xs:QName and xs:NOTATION.

Example: Using a Constructor Function for a User-Defined Atomic Type

Consider a situation where the static context contains an atomic type called hatSize defined in a schema whose target namespace is bound to the prefix eg. In such a case the following constructor function is available to users:

eg:hatSize(
$valueas xs:anyAtomicType
) as my:hatSize?

The resulting function may be used in an expression such as eg:hatSize("10½").

Note:

To construct an instance of a user-defined type that is not in a namespace, it is possible to use an EQName (for example Q{}hatsize(17)). Alternatives are to use a cast expression (17 cast as hatsize) or (if the host language allows it) to undeclare the default function namespace.

22.623.6 Constructor functions for named record types

Changes in 4.0 (next | previous)

  1. Constructor functions for named record types have been introduced.   [Issue 617 PR 953 20 February 2024]

Both XQuery 4.0 and XSLT 4.0 provide syntax to declare named record types; such a declaration implicitly adds a constructor function for values of that type to the (See 2.1.1 Static Context XP31).

For example, if there is a named item type with the XQuery definition:

declare record my:location (
  latitude  as xs:double,
  longitude as xs:double
)

then there will be a function definition equivalent to:

declare function my:location (
  $latitude  as xs:double,
  $longitude as xs:double
) as my:location {
  { 'latitude': $latitude, 'longitude': $longitude }
}

Equivalently using XSLT syntax, if there is a named item type with the XSLT definition:

<xsl:record name="my:location"
  as="record(latitude as xs:double, longitude as xs:double)"/>

then there will be a function definition equivalent to:

<xsl:function name="my:location" as="my:location">
  <xsl:param name="latitude" as="xs:double"/>
  <xsl:param name="longitude" as="xs:double"/>
  <xsl:map>
    <xsl:map-entry key="'latitude'" select="$latitude"/>
    <xsl:map-entry key="'longitude'" select="$longitude"/>
  </xsl:map>
</xsl:function>

The rules defining the relationship of the function definition to the record type are given for XQuery 4.0 in [XQuery 4.0: An XML Query Language] section 5.20.2 Constructor Functions for Named Record Types.

Editorial note 
TODO: Add cross-reference to XSLT here. Anticipates resolution of issue #1485.

2324 Casting

Constructor functions and cast expressions accept an expression and return a value of a given type. They both convert a source value SV, of a source type, ST to a target value TV, of the given target type TT.

Constructor functions and cast expressions have identical semantics but different syntax. The name of the constructor function is the same as the name of the built-in [XML Schema Part 2: Datatypes Second Edition] datatype or the datatype defined in 2.7 Schema Information DM31 of [XQuery and XPath Data Model (XDM) 4.0] (see 22.123.1 Constructor functions for XML Schema built-in atomic types) or the user-derived datatype (see 22.523.5 Constructor functions for user-defined atomic and union types) that is the target for the conversion, and the semantics are exactly the same as for a cast expression; for example, xs:date("2003-01-01") means exactly the same as "2003-01-01" cast as xs:date?.

The cast expression takes a type name to indicate the target type of the conversion. See 3.14.2 Cast XP31. If the type name allows the empty sequence and the expression to be cast is the empty sequence, the empty sequence is returned. If the type name does not allow the empty sequence and the expression to be cast is the empty sequence, a type error is raised [err:XPTY0004]XP.

Where the argument to a cast is a literal, the result of the function may be evaluated statically; if an error is encountered during such evaluation, it may be reported as a static error.

The general rules for casting from primitive types to primitive types are defined in 23.124.1 Casting from primitive types to primitive types, and subsections describe the rules for specific target types. The general rules for casting from xs:string (and xs:untypedAtomic) follow in 23.224.2 Casting from xs:string and xs:untypedAtomic. Casting to non-primitive types, including atomic types derived by restriction, union types, and list types, is described in 23.324.3 Casting involving non-primitive types. Casting from derived types is defined in 23.3.424.3.4 Casting from derived types to parent types, 23.3.524.3.5 Casting within a branch of the type hierarchy and 23.3.624.3.6 Casting across the type hierarchy.

Casting is not supported to or from xs:anySimpleType. Casting to xs:anySimpleType is not permitted and raises a static error: [err:XPST0080]XP.

Similarly, casting is not supported to or from xs:anyAtomicType and will raise a static error: [err:XPST0080]XP. There are no atomic items with the type annotation xs:anyAtomicType, although this can be a statically inferred type.

23.124.1 Casting from primitive types to primitive types

Changes in 4.0 (next | previous)

  1. This section now uses the term primitive type strictly to refer to the 20 atomic types that are not derived by restriction from another atomic type: that is, the 19 primitive atomic types defined in XSD, plus xs:untypedAtomic. The three types xs:integer, xs:dayTimeDuration, and xs:yearMonthDuration, which have custom casting rules but are not strictly-speaking primitive, are now handled in other subsections.   [Issue 1401 PR 1409]

This section defines casting between primitive types (specifically, the 19 primitive types defined in [XML Schema Part 2: Datatypes Second Edition] plus xs:untypedAtomic. The type conversions that are supported between primitive atomic types are indicated in the table below; casts between other (non-primitive) types are defined in terms of these primitives.

Where the target type TT is a primitive type, the result TV will always be an instance of TT. The result may also be an instance of a type derived from TT: for example casting an xs:NCNameSV to xs:stringmay return SV unchanged, with its original type annotation.

In this table, there is a row for each primitive type acting as the source of the conversion and there is a column for each primitive type acting as the target of the conversion. The intersections of rows and columns contain one of three characters:

  • Y indicates that a conversion from values of the type to which the row applies to the type to which the column applies is supported;

  • N indicates that there are no supported conversions from values of the type to which the row applies to the type to which the column applies;

  • M indicates that a conversion from values of the type to which the row applies to the type to which the column applies may succeed for some values in the value space and fail for others.

There is no row or column for xs:untypedAtomic because the casting rules are exactly the same as for xs:string. When casting from xs:string or xs:untypedAtomic the semantics in 23.224.2 Casting from xs:string and xs:untypedAtomic apply, regardless of target type.

[XML Schema Part 2: Datatypes Second Edition] defines xs:NOTATION as an abstract type. Thus, casting to xs:NOTATION from any other type including xs:NOTATION is not permitted and raises a static error [err:XPST0080]XP. However, casting from one subtype of xs:NOTATION to another subtype of xs:NOTATION is permitted.

Casting is not supported to or from xs:anySimpleType. Thus, there is no row or column for this type in the table below. For any node that has not been validated or has been validated as xs:anySimpleType, the typed value of the node is an atomic item of type xs:untypedAtomic. There are no atomic items with the type annotation xs:anySimpleType at runtime. Casting to xs:anySimpleType is not permitted and raises a static error: [err:XPST0080]XP.

Similarly, casting is not supported to or from xs:anyAtomicType and will raise a static error: [err:XPST0080]XP. There are no atomic items with the type annotation xs:anyAtomicType at runtime, although this can be a statically inferred type.

If casting is attempted from an ST to a TT for which casting is not supported, as defined in the table below, a type error is raised [err:XPTY0004]XP.

In the following table, the columns and rows are identified by short codes that identify simple types as follows:

aURI = xs:anyURI
b64 = xs:base64Binary
bool = xs:boolean
dat = xs:date
gDay = xs:gDay
dbl = xs:double
dec = xs:decimal
dT = xs:dateTime
dur = xs:duration
flt = xs:float
hxB = xs:hexBinary
gMD = xs:gMonthDay
gMon = xs:gMonth
NOT = xs:NOTATION
QN = xs:QName
str = xs:string
tim = xs:time
gYM = xs:gYearMonth
gYr = xs:gYear

In the following table, the notation “S\T” indicates that the source (“S”) of the conversion is indicated in the column below the notation and that the target (“T”) is indicated in the row to the right of the notation.

S\TstrfltdbldecdurdTtimdatgYMgYrgMDgDaygMonboolb64hxBaURIQNNOT
strYMMMMMMMMMMMMMMMMMM
fltYYYMNNNNNNNNNYNNNNN
dblYYYMNNNNNNNNNYNNNNN
decYYYYNNNNNNNNNYNNNNN
durYNNNYNNNNNNNNNNNNNN
dTYNNNNYYYYYYYYNNNNNN
timYNNNNNYNNNNNNNNNNNN
datYNNNNYNYYYYYYNNNNNN
gYMYNNNNNNNYNNNNNNNNNN
gYrYNNNNNNNNYNNNNNNNNN
gMDYNNNNNNNNNYNNNNNNNN
gDayYNNNNNNNNNNYNNNNNNN
gMonYNNNNNNNNNNNYNNNNNN
boolYYYYNNNNNNNNNYNNNNN
b64YNNNNNNNNNNNNNYYNNN
hxBYNNNNNNNNNNNNNYYNNN
aURIYNNNNNNNNNNNNNNNYNN
QNYNNNNNNNNNNNNNNNNYM
NOTYNNNNNNNNNNNNNNNNYM

23.1.124.1.1 Casting to xs:untypedAtomic

Any atomic item SV can be cast to xs:untypedAtomic.

The effect is the same as casting to xs:string (see 23.1.224.1.2 Casting to xs:string) and then returning the xs:untypedAtomic value comprising the same sequence of characters.

23.1.224.1.2 Casting to xs:string

Any atomic item SV can be cast to xs:string.

The resulting xs:string value TV depends on the source type ST as follows.

To cast as xs:untypedAtomic the value is cast as xs:string, as described above, and the type annotation changed to xs:untypedAtomic.

23.1.2.124.1.2.1 Casting numeric values to xs:string

The following rules apply when the source type ST is xs:decimal, xs:double, or xs:float, or any subtype of these including xs:integer.

  1. If SV is an instance of xs:decimal, then the canonical representation of SV is returned, as defined in [XSD 1.1 Part 2]. Specifically, see decimalCanonicalMap.

    Note:

    Unlike previous versions of this specification, no special rule is given for the case where SV is an instance of xs:integer. This is because the general rule for xs:decimal gives the same result. The result in this case will be a sequence of decimal digits in the range U+0030 (DIGIT ZERO, 0) to U+0039 (DIGIT NINE, 9) , optionally preceded by a minus sign, with no leading zeroes. For example: 42, -1, 0, or 1000000000.

    Note:

    An xs:decimal that is equal to an integer is converted to a string as if it were first cast to an xs:integer. Specifically, there will be no decimal point and no fractional part.

    If the value is not equal to an integer, then there will be a decimal point and a fractional part, which will be a sequence of decimal digits with no trailing zeroes. For example: 42.3, -1.5, or 0.00001.

  2. If SV is an instance of xs:float or xs:double, then:

    1. TV will be an xs:string in the lexical space of xs:double or xs:float that when converted to an xs:double or xs:float under the rules of 23.224.2 Casting from xs:string and xs:untypedAtomic produces a value that is equal to SV, or is NaN if SV is NaN. In addition, TV must satisfy the constraints in the following sub-bullets.

      1. If SV has an absolute value that is greater than or equal to 0.000001 (one millionth) and less than 1000000 (one million), then the value is converted to an xs:decimal and the resulting xs:decimal is converted to an xs:string according to the rules above, as though using an implementation of xs:decimal that imposes no limits on the totalDigits or fractionDigits facets.

      2. If SV has the value positive or negative zero, TV is "0" or "-0" respectively.

      3. If SV is positive or negative infinity, TV is the string "INF" or "-INF" respectively.

      4. In other cases, the result consists of a mantissa, which has the lexical form of an xs:decimal, followed by the letter "E", followed by an exponent which has the lexical form of an xs:integer. Leading zeroes and "+" signs are prohibited in the exponent. For the mantissa, there must be a decimal point, and there must be exactly one digit before the decimal point, which must be non-zero. The "+" sign is prohibited. There must be at least one digit after the decimal point. Apart from this mandatory digit, trailing zero digits are prohibited.

    Note:

    The above rules allow more than one representation of the same value. For example, the xs:float value whose exact decimal representation is 1.26743223E15 might be represented by any of the strings "1.26743223E15", "1.26743222E15" or "1.26743224E15" (inter alia). It is implementation-dependent which of these representations is chosen.

Note:

The string representations of numeric values are backwards compatible with XPath 1.0 except for the special values positive and negative infinity, negative zero and values outside the range 1.0e-6 to 1.0e+6.

23.1.2.224.1.2.2 Casting date/time values to xs:string

Changes in 4.0 (next | previous)

  1. The rules for conversion of dates and times to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since these deliver exactly the same result as the XPath 3.1 rules.   [Issue 1401 PR 1409]

If SV is an instance of xs:dateTime, xs:date, xs:time, xs:gYear, xs:gYearMonth, xs:gMonth, xs:gMonthDay, or xs:gDay, then TV is the canonical representation of SV as defined in [XSD 1.1 Part 2].

Note:

The result TV includes the original timezone if a timezone is present.

All these data types contain different combinations of the components year, month, day, hour, minute, second, and timezone; all the components relevant to the data type (with the exception of the timezone) are output, and the results are concatenated together with suitable punctuation. Specifically:

  1. The year component is represented as a xs:string of four digits, or more if needed. A leading minus sign is present for BCE years.

  2. The month, day, hour and minute components are represented as two digits (with a leading zero if needed). For example, February is represented as 02.

    The hours component will never be "24": midnight is always represented as "00:00:00".

  3. The second component is output using as a two-digit integer if it is a whole number (for example, 30, 05, or 00), or if it is fractional, as two digits followed by a decimal point followed by as many digits as are necessary, with no trailing zeroes (for example 30.5 or 00.001).

  4. The timezone component, if present, is cast to xs:string by applying the function eg:convertTZtoString given in 23.1.524.1.5 Casting to date and time types. Examples are Z, +01:00, -05:00, or +05:30.

.

23.1.2.324.1.2.3 Casting xs:duration values to xs:string

Changes in 4.0 (next | previous)

  1. The rules for conversion of durations to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since the XSD 1.1 rules deliver exactly the same result as the XPath 3.1 rules.   [Issue 1401 PR 1409]

If SV is an instance of xs:duration (including its subtypes xs:yearMonthDuration and xs:dayTimeDuration), then TV is the canonical representation of SV as defined in [XSD 1.1 Part 2]. Specifically, see durationCanonicalMap.

Note:

The rules have the effect of normalizing the value so that the number of months is always less than 12, the number of hours less than 24, and the number of minutes and seconds less than 60. Zero-valued components are omitted. Fractional seconds follow the same rules as xs:decimal. For example, the duration P15MT30H is represented as P1Y3M1DT6H. A zero-length duration is output as PT0S.

Note:

At the time of writing, the published XSD 1.1 recommendation contains cut-and-paste errors in the definition of the dayTimeDuration canonical mapping. The binding of variable s should be to dt's ·seconds· (not ·months·) component, and the return expression given as sgn & 'P' & ·duYearMonthCanonicalFragmentMap·(|s|) should read sgn & 'P' & ·duDayTimeCanonicalFragmentMap·(|s|)

In reading these XSD formulations, be aware that a & b represents string concatenation, while |s| computes the absolute value of a number.

23.1.324.1.3 Casting to numeric types

This section defines the rules for casting to the primitive numeric types xs:float, xs:double, and xs:decimal. Rules for casting to the derived type xs:integer are given in 23.3.224.3.2 Casting to xs:integer.

23.1.3.124.1.3.1 Casting to xs:float

When a value of any simple type is cast as xs:float, the xs:floatTV is derived from the ST and the SV as follows:

  • If ST is xs:float, then TV is SV and the conversion is complete.

  • If ST is xs:double, then TV is obtained as follows:

    • if SV is the xs:double value INF, -INF, NaN, positive zero, or negative zero, then TV is the xs:float value INF, -INF, NaN, positive zero, or negative zero respectively.

    • otherwise, SV can be expressed in the form m × 2^e where the mantissa m and exponent e are signed xs:integers whose value range is defined in [XML Schema Part 2: Datatypes Second Edition], and the following rules apply:

      • if m (the mantissa of SV) is outside the permitted range for the mantissa of an xs:float value (-2^24-1 to +2^24-1), then it is divided by 2^N where N is the lowest positive xs:integer that brings the result of the division within the permitted range, and the exponent e is increased by N. This is integer division (in effect, the binary value of the mantissa is truncated on the right). Let M be the mantissa and E the exponent after this adjustment.

      • if E exceeds 104 (the maximum exponent value in the value space of xs:float) then TV is the xs:float value INF or -INF depending on the sign of M.

      • if E is less than -149 (the minimum exponent value in the value space of xs:float) then TV is the xs:float value positive or negative zero depending on the sign of M

      • otherwise, TV is the xs:float value M × 2^E.

  • If ST is xs:decimal, or xs:integer, then TV is xs:float(SV cast as xs:string) and the conversion is complete.

  • If ST is xs:boolean, SV is converted to 1.0E0 if SV is true and to 0.0E0 if SV is false and the conversion is complete.

  • If ST is xs:untypedAtomic or xs:string, see 23.224.2 Casting from xs:string and xs:untypedAtomic.

    Note:

    XSD 1.1 adds the value +INF to the lexical space, as an alternative to INF. XSD 1.1 also adds negative zero to the value space.

Note:

Implementations should return negative zero for xs:float("-0.0E0"). But because [XML Schema Part 2: Datatypes Second Edition] does not distinguish between the values positive zero and negative zero. Implementations may return positive zero in this case.

23.1.3.224.1.3.2 Casting to xs:double

When a value of any simple type is cast as xs:double, the xs:double value TV is derived from the ST and the SV as follows:

Note:

Implementations should return negative zero for xs:double("-0.0E0"). But because [XML Schema Part 2: Datatypes Second Edition] does not distinguish between the values positive zero and negative zero. Implementations may return positive zero in this case.

23.1.3.324.1.3.3 Casting to xs:decimal

This section defines the rules for casting to the primitive type xs:decimal. The rules are also invoked implicitly as part of the process of converting to types derived from xs:decimal. There are special rules, however, if the target type TT is xs:integer, or a type derived from xs:integer: those rules are given in 23.3.224.3.2 Casting to xs:integer.

When the target type TT is xs:decimal, the resulting xs:decimal value TV is derived from ST and SV as follows:

23.1.424.1.4 Casting to duration types

This section defines the rules for casting to the primitive duration type xs:duration. Rules for casting to the derived types xs:yearMonthDuration and xs:dayTimeDuration are given in 23.3.324.3.3 Casting to xs:yearMonthDuration and xs:dayTimeDuration.

23.1.524.1.5 Casting to date and time types

In several situations, casting to date and time types requires the extraction of a component from SV or from the result of fn:current-dateTime and converting it to an xs:string. These conversions must follow certain rules. For example, converting an xs:integer year value requires converting to an xs:string with four or more characters, preceded by a minus sign if the value is negative.

This document defines four functions to perform these conversions. These functions are for illustrative purposes only and make no recommendations as to style or efficiency. References to these functions from the following text are not normative.

The arguments to these functions come from functions defined in this document. Thus, the functions below assume that they are correct and do no range checking on them.

declare function eg:convertYearToString($year as xs:integer) as xs:string {
  let $plusMinus := if ($year >= 0) then "" else "-"
  let $yearString := abs($year) cast as xs:string
  let $length := string-length($yearString)
  return if ($length = 1) then concat($plusMinus, "000", $yearString)
         else if ($length = 2) then concat($plusMinus, "00", $yearString)
         else if ($length = 3) then concat($plusMinus, "0", $yearString)
         else concat($plusMinus, $yearString)
};
declare function eg:convertTo2CharString($value as xs:integer) as xs:string {
  let $string := $value cast as xs:string
  return if (string-length($string) = 1) then concat("0", $string)
         else $string
};
declare function eg:convertSecondsToString($seconds as xs:decimal) as xs:string {
  let $string := $seconds cast as xs:string
  let $intLength := string-length(($seconds cast as xs:integer) cast as xs:string)
  return if ($intLength = 1) then concat("0", $string)
         else $string
};
declare function eg:convertTZtoString($tz as xs:dayTimeDuration?) as xs:string {
  if (empty($tz)) then ""
  else if ($tz eq xs:dayTimeDuration('PT0S')) then "Z"
  else let $tzh := hours-from-duration($tz)
       let $tzm := minutes-from-duration($tz)
       let $plusMinus := if ($tzh >= 0) then "+" else "-"
       let $tzhString := eg:convertTo2CharString(abs($tzh))
       let $tzmString := eg:convertTo2CharString(abs($tzm))
       return concat($plusMinus, $tzhString, ":", $tzmString)
};

Conversion from primitive types to date and time types follows the rules below.

  1. When a value of any primitive type is cast as xs:dateTime, the xs:dateTime value TV is derived from ST and SV as follows:

  2. When a value of any primitive type is cast as xs:time, the xs:time value TV is derived from ST and SV as follows:

  3. When a value of any primitive type is cast as xs:date, the xs:date value TV is derived from ST and SV as follows:

  4. When a value of any primitive type is cast as xs:gYearMonth, the xs:gYearMonth value TV is derived from ST and SV as follows:

  5. When a value of any primitive type is cast as xs:gYear, the xs:gYear value TV is derived from ST and SV as follows:

  6. When a value of any primitive type is cast as xs:gMonthDay, the xs:gMonthDay value TV is derived from ST and SV as follows:

  7. When a value of any primitive type is cast as xs:gDay, the xs:gDay value TV is derived from ST and SV as follows:

  8. When a value of any primitive type is cast as xs:gMonth, the xs:gMonth value TV is derived from ST and SV as follows:

23.1.624.1.6 Casting to xs:boolean

When the target type TT is xs:boolean, the resulting xs:boolean value TV is derived from the source value SV as follows:

23.1.724.1.7 Casting to xs:base64Binary and xs:hexBinary

Values of type xs:base64Binary can be cast as xs:hexBinary and vice versa, since the two types have the same value space. Casting to xs:base64Binary and xs:hexBinary is also supported from the same type and from xs:untypedAtomic, xs:string and subtypes of xs:string using [XML Schema Part 2: Datatypes Second Edition] semantics.

23.1.824.1.8 Casting to xs:anyURI

Casting to xs:anyURI is supported only from the same type, xs:untypedAtomic or xs:string.

When a value of any primitive type is cast as xs:anyURI, the xs:anyURI value TV is derived from the ST and SV as follows:

23.1.924.1.9 Casting to xs:QName and xs:NOTATION

Casting from xs:string or xs:untypedAtomic to xs:QName or xs:NOTATION is described in 23.224.2 Casting from xs:string and xs:untypedAtomic.

It is also possible to cast from xs:NOTATION to xs:QName, or from xs:QName to any type derived by restriction from xs:NOTATION. (Casting to xs:NOTATION itself is not allowed, because xs:NOTATION is an abstract type.) The resulting xs:QName or xs:NOTATION has the same prefix, local name, and namespace URI parts as the supplied value.

Note:

See 22.223.2 Constructor functions for xs:QName and xs:NOTATION for a discussion of how the combination of atomization and casting might not produce the desired effect.

23.1.1024.1.10 Casting to xs:ENTITY

[XML Schema Part 2: Datatypes Second Edition] says that “The value space of ENTITY is the set of all strings that match the NCName production ... and have been declared as an unparsed entity in a document type definition.” However, [XSL Transformations (XSLT) Version 4.0] and [XQuery 4.0: An XML Query Language] do not check that constructed values of type xs:ENTITY match declared unparsed entities. Thus, this rule is relaxed in this specification and, in casting to xs:ENTITY and types derived from it, no check is made that the values correspond to declared unparsed entities.

23.224.2 Casting from xs:string and xs:untypedAtomic

Changes in 4.0 (next | previous)

  1. When casting from a string to a duration or time or dateTime, it is now specified that when there are more digits in the fractional seconds than the implementation is able to retain, excess digits are truncated. Rounding upwards (which could affect the number of minutes or hours in the value) is not permitted.   [Issue 1089 PR 1090 19 March 2024]

This section applies when the supplied value SV is an instance of xs:string or xs:untypedAtomic, including types derived from these by restriction. If the value is xs:untypedAtomic, it is treated in exactly the same way as a string containing the same sequence of characters.

The supplied string is mapped to a typed value of the target type as defined in [XML Schema Part 2: Datatypes Second Edition]. Whitespace normalization is applied as indicated by the whiteSpace facet for the datatype. The resulting whitespace-normalized string must be a valid lexical form for the datatype. The semantics of casting follow the rules of XML Schema validation. For example, "13" cast as xs:unsignedInt returns the xs:unsignedInt typed value 13. This could also be written xs:unsignedInt("13").

The target type can be any simple type other than an abstract type. Specifically, it can be a type whose variety is atomic, union, or list. In each case the effect of casting to the target type is the same as constructing an element with the supplied value as its content, validating the element using the target type as the governing type, and atomizing the element to obtain its typed value.

When the target type is a derived type that is restricted by a pattern facet, the lexical form is first checked against the pattern before further casting is attempted (See 23.3.124.3.1 Casting to derived types). If the lexical form does not conform to the pattern, a dynamic error [err:FORG0001] is raised.

For example, consider a user-defined type my:boolean which is derived by restriction from xs:boolean and specifies the pattern facet value="0|1". The expression "true" cast as my:boolean would fail with a dynamic error [err:FORG0001].

Facets other than pattern are checked after the conversion. For example if there is a user-defined datatype called my:height defined as a restriction of xs:integer with the facet <maxInclusive value="84"/>, then the expression "100" cast as my:height would fail with a dynamic error [err:FORG0001].

Casting to the types xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType is not permitted because these types are abstract (they have no immediate instances).

Special rules apply when casting to namespace-sensitive types. The types xs:QName and xs:NOTATION are namespace-sensitive. Any type derived by restriction from a namespace-sensitive type is itself namespace-sensitive, as is any union type having a namespace-sensitive type among its members, and any list type having a namespace-sensitive type as its item type. For details, see 22.223.2 Constructor functions for xs:QName and xs:NOTATION.

Note:

Since version 3.0 of this specification, casting has been allowed between xs:QName and xs:NOTATION in either direction; this was not permitted in previous Recommendations. Version 3.0 also removed the rule that only a string literal (rather than a dynamic string) may be cast to an xs:QName

When casting to a numeric type:

  • If the value is too large or too small to be accurately represented by the implementation, it is handled as an overflow or underflow as defined in 4.2 Arithmetic operators on numeric values.

  • If the target type is xs:float or xs:double, the string -0 (and equivalents such as -0.0 or -000) should be converted to the value negative zero. However, if the implementation is reliant on an implementation of XML Schema 1.0 in which negative zero is not part of the value space for these types, these lexical forms may be converted to positive zero.

In casting to xs:decimal or to a type derived from xs:decimal, if the value is not too large or too small but nevertheless cannot be represented accurately with the number of decimal digits available to the implementation, the implementation may round to the nearest representable value or may raise a dynamic error [err:FOCA0006]. The choice of rounding algorithm and the choice between rounding and error behavior is implementation-defined.

When casting to xs:duration, xs:dateTime, or xs:time, if the seconds component has more fractional digits than are supported by the implementation, excess digits must be truncated. This rule ensures that components other than the seconds component are unaffected: for example xs:dateTime('2023-12-31T23:59:59.999999999') is guaranteed to deliver an xs:dateTime value whose year component is 2023 rather than 2024.

Note:

Implementations are required to support millisecond precision or greater.

In casting to xs:date, xs:dateTime, xs:gYear, or xs:gYearMonth (or types derived from these), if the value is too large or too small to be represented by the implementation, a dynamic error [err:FODT0001] is raised.

In casting to a duration value, if the value is too large or too small to be represented by the implementation, a dynamic error [err:FODT0002] is raised.

For xs:anyURI, the extent to which an implementation validates the lexical form of xs:anyURI is implementation-dependent.

If the cast fails for any other reason, a dynamic error [err:FORG0001] is raised.

23.324.3 Casting involving non-primitive types

Casting from xs:string and xs:untypedAtomic to any other type (primitive or non-primitive) has been described in 23.224.2 Casting from xs:string and xs:untypedAtomic. This section defines how other casts to non-primitive types operate, including casting to types derived by restriction, to union types, and to list types.

23.3.124.3.1 Casting to derived types

Casting a value to a derived type can be separated into a number of cases. In these rules:

  • The types xs:integer, xs:yearMonthDuration, and xs:dayTimeDuration are treated as quasi-primitive types (alongside the 20 truly primitive types).

  • For any atomic type T, let P(T) denote the most specific primitive or quasi-primitive type such that itemType-subtype(T, P(T)) is true.

The rules are then:

  1. When the source type ST is the same type as the target type TT: this case always succeeds, returning the source value SV unchanged.

  2. When itemType-subtype(ST, TT) is true: see 23.3.424.3.4 Casting from derived types to parent types.

  3. When TT is the quasi-primitive type xs:integer and SV is an instance of xs:numeric: see 23.3.224.3.2 Casting to xs:integer.

  4. When TT is the quasi-primitive type xs:yearMonthDuration or xs:dayTimeDuration and SV is an instance of xs:duration: see 23.3.324.3.3 Casting to xs:yearMonthDuration and xs:dayTimeDuration.

  5. When P(ST) is the same type as P(TT): see 23.3.524.3.5 Casting within a branch of the type hierarchy.

  6. Otherwise (P(ST) is not the same type as P(TT)): see 23.3.624.3.6 Casting across the type hierarchy.

23.3.224.3.2 Casting to xs:integer

When an atomic item SV is cast as xs:integer, the resulting xs:integer value TV is obtained as follows:

Note:

When casting to a subtype of xs:integer (for example, xs:long), the rules in 23.3.124.3.1 Casting to derived types apply. Note, however, that these rules treat xs:integer as a quasi-primitive type.

23.3.324.3.3 Casting to xs:yearMonthDuration and xs:dayTimeDuration

When the source value SV is an instance of xs:duration (including any subtype of xs:duration), then:

  • If the target type TT is xs:yearMonthDuration, the result is an instance of xs:yearMonthDuration whose months component is equal to the months component of SV. The seconds component of SV is ignored.

  • If the target type TT is xs:dayTimeDuration, the result is an instance of xs:dayTimeDuration whose seconds component is equal to the seconds component of SV. The months component of SV is ignored.

In all other cases, the general rules of 23.3.124.3.1 Casting to derived types apply.

Note:

In general, casting to xs:yearMonthDuration or xs:dayTimeDuration loses information.

Note:

When casting to a subtype of xs:dayTimeDuration or xs:yearMonthDuration, the rules in 23.3.124.3.1 Casting to derived types apply. Note, however, that these rules treat xs:dayTimeDuration and xs:yearMonthDuration as quasi-primitive types.

23.3.424.3.4 Casting from derived types to parent types

It is always possible to cast an atomic item A to a type T if the relation A instance of T is true, provided that T is not an abstract type.

For example, it is possible to cast an xs:unsignedShort to an xs:unsignedInt, to an xs:integer, to an xs:decimal, or to a union type whose member types are xs:integer and xs:double.

Since the value space of the original type is a subset of the value space of the target type, such a cast is always successful.

For the expression A instance of T to be true, T must be either an atomic type, or a union type that has no constraining facets. It cannot be a list type, nor a union type derived by restriction from another union type, nor a union type that has a list type among its member types.

The result will have the same value as the original, but will have a new type annotation:

  • If T is an atomic type, then the type annotation of the result is T.

  • If T is a union type, then the type of the result is an atomic type M such that M is one of the atomic types in the transitive membership of the union type T and A instance of M is true; if there is more than one type M that satisfies these conditions (which could happen, for example, if T is the union of two overlapping types such as xs:int and xs:positiveInteger) then the first one is used, taking the member types in the order in which they appear within the definition of the union type.

23.3.524.3.5 Casting within a branch of the type hierarchy

It is possible to cast an SV to a TT if the type of the SV and the TT type are both derived by restriction (directly or indirectly) from the same primitive type, provided that the supplied value conforms to the constraints implied by the facets of the target type. This includes the case where the target type is derived from the type of the supplied value, as well as the case where the type of the supplied value is derived from the target type. For example, an instance of xs:byte can be cast as xs:unsignedShort, provided the value is not negative.

If the value does not conform to the facets defined for the target type, then a dynamic error is raised [err:FORG0001]. See [XML Schema Part 2: Datatypes Second Edition]. In the case of the pattern facet (which applies to the lexical space rather than the value space), the pattern is tested against the canonical representation of the value, as defined for the source type (or the result of casting the value to an xs:string, in the case of types that have no canonical representation defined for them).

Note that this will cause casts to fail if the pattern excludes the canonical lexical representation of the source type. For example, if the type my:distance is defined as a restriction of xs:decimal with a pattern that requires two digits after the decimal point, casting of an xs:integer to my:distance will always fail, because the canonical representation of an xs:integer does not conform to this pattern.

In some cases, casting from a parent type to a derived type requires special rules. See 23.1.424.1.4 Casting to duration types for rules regarding casting to xs:yearMonthDuration and xs:dayTimeDuration. See 23.1.1024.1.10 Casting to xs:ENTITY, below, for casting to xs:ENTITY and types derived from it.

23.3.624.3.6 Casting across the type hierarchy

When the ST and the TT are derived, directly or indirectly, from different primitive types, this is called casting across the type hierarchy. Casting across the type hierarchy is logically equivalent to three separate steps performed in order. Errors can occur in either of the latter two steps.

  1. Cast the SV, up the hierarchy, to the primitive type of the source, as described in 23.3.424.3.4 Casting from derived types to parent types.

    1. If SV is an instance of xs:string or xs:untypedAtomic, check its value against the pattern facet of TT, and raise a dynamic error [err:FORG0001] if the check fails.

  2. Let P(TT) be the most specific primitive or quasi-primitive type of which TT is a subtype, as described in 23.3.124.3.1 Casting to derived types.

    Cast the value to P(TT), as described in 23.124.1 Casting from primitive types to primitive types if P(TT) is primitive, or as described in 23.3.124.3.1 Casting to derived types if P(TT) is quasi-primitive.

    If TT is derived from xs:NOTATION, assume for the purposes of this rule that casting to xs:NOTATION succeeds.

  3. Cast the value down to the target type TT, as described in 23.3.524.3.5 Casting within a branch of the type hierarchy

23.3.724.3.7 Casting to union types

If the target type of a cast expression (or a constructor function) is a type with variety union, the supplied value must be one of the following:

  1. A value of type xs:string or xs:untypedAtomic. This case follows the general rules for casting from strings, and has already been described in 23.224.2 Casting from xs:string and xs:untypedAtomic.

    If the union type has a pattern facet, the pattern is tested against the supplied value after whitespace normalization, using the whiteSpace normalization rules of the member datatype against which validation succeeds.

  2. A value that is an instance of one of the atomic types in the transitive membership of the union type, and of the union type itself. This case has already been described in 23.3.424.3.4 Casting from derived types to parent types

    This situation only applies when the value is an instance of the union type, which means it will never apply when the union is derived by facet-based restriction from another union type.

  3. A value that is castable to one or more of the atomic types in the transitive membership of the union type (in the sense that the castable as operator returns true).

    In this case the supplied value is cast to each atomic type in the transitive membership of the union type in turn (in the order in which the member types appear in the declaration) until one of these casts is successful; if none of them is successful, a dynamic error occurs [err:FORG0001]. If the union type has constraining facets then the resulting value must satisfy these facets, otherwise a dynamic error occurs [err:FORG0001].

    If the union type has a pattern facet, the pattern is tested against the canonical representation of the result value.

    Only the atomic types in the transitive membership of the union type are considered. The union type may have list types in its transitive membership, but (unless the supplied value is of type xs:string or xs:untypedAtomic, in which case the rules in 23.224.2 Casting from xs:string and xs:untypedAtomic apply), any list types in the membership are effectively ignored.

If more than one of these conditions applies, then the casting is done according to the rules for the first condition that applies.

If none of these conditions applies, the cast fails with a dynamic error [err:FORG0001].

Example: consider a type U whose member types are xs:integer and xs:date.

  • The expression "123" cast as U returns the xs:integer value 123.

  • The expression current-date() cast as U returns the current date as an instance of xs:date.

  • The expression 23.1 cast as U returns the xs:integer value 23.

Example: consider a type V whose member types are xs:short and xs:negativeInteger.

  • The expression "-123" cast as V returns the xs:short value -123.

  • The expression "-100000" cast as V returns the xs:negativeInteger value -100000.

  • The expression 93.7 cast as V returns the xs:short value 93.

  • The expression "93.7" cast as V raises a dynamic error [err:FORG0001] on the grounds that the string "93.7" is not in the lexical space of the union type.

Example: consider a type W that is derived from the above type V by restriction, with a pattern facet of -?\d\d.

  • The expression "12" cast as V returns the xs:short value 12.

  • The expression "123" cast as V raises an dynamic error [err:FORG0001] on the grounds that the string "123" does not match the pattern facet.

23.3.824.3.8 Casting to list types

If the target type of a cast expression (or a constructor function) is a type with variety list, the supplied value must be of type xs:string or xs:untypedAtomic. The rules follow the general principle for all casts from xs:string outlined in 23.224.2 Casting from xs:string and xs:untypedAtomic.

If the supplied value is not of type xs:string or xs:untypedAtomic, a type error is raised [err:XPTY0004]XP.

The semantics of the operation are consistent with validation: that is, the effect of casting a string S to a list type L is the same as constructing an element or attribute node whose string value is S, validating it using L as the governing type, and atomizing the resulting node. The result will always be either failure, or a sequence of zero or more atomic items each of which is an instance of the item type of L (or if the item type of L is a union type, an instance of one of the atomic types in its transitive membership).

If the item type of the list type is namespace-sensitive, then the namespace bindings in the static context will be used to resolve any namespace prefix, in the same way as when the target type is xs:QName.

If the list type has a pattern facet, the pattern must match the supplied value after collapsing whitespace (an operation equivalent to the use of the fn:normalize-space function).

For example, the expression cast "A B C D" as xs:NMTOKENS produces a sequence of four xs:NMTOKEN values, ("A", "B", "C", "D").

For example, given a user-defined type my:coordinates defined as a list of xs:integer with the facet <xs:length value="2"/>, the expression my:coordinates("2 -1") will return a sequence of two xs:integer values (2, -1), while the expression my:coordinates("1 2 3") will result in a dynamic error because the length of the list does not conform to the length facet. The expression my:coordinates("1.0 3.0") will also fail because the strings 1.0 and 3.0 are not in the lexical space of xs:integer.

B Error codes

The error text provided with these errors is non-normative.

err:FOAP0001, Wrong number of arguments.

Raised when fn:apply is called and the arity of the supplied function is not the same as the number of members in the supplied array.

err:FOAR0001, Division by zero.

This error is raised whenever an attempt is made to divide by zero.

err:FOAR0002, Numeric operation overflow/underflow.

This error is raised whenever numeric operations result in an overflow or underflow.

err:FOAY0001, Array index out of bounds.

This error is raised when an integer used to select a member of an array is outside the range of values for that array.

err:FOAY0002, Negative array length.

This error is raised when the $length argument to array:subarray is negative.

err:FOCA0001, Input value too large for decimal.

Raised when casting to xs:decimal if the supplied value exceeds the implementation-defined limits for the datatype.

err:FOCA0002, Invalid lexical value.

Raised by fn:resolve-QName and fn:QName when a supplied value does not have the lexical form of a QName or URI respectively; and when casting to decimal, if the supplied value is NaN or Infinity.

err:FOCA0003, Input value too large for integer.

Raised when casting to xs:integer if the supplied value exceeds the implementation-defined limits for the datatype.

err:FOCA0005, NaN supplied as float/double value.

Raised when multiplying or dividing a duration by a number, if the number supplied is NaN.

err:FOCA0006, String to be cast to decimal has too many digits of precision.

Raised when casting a string to xs:decimal if the string has more digits of precision than the implementation can represent (the implementation also has the option of rounding).

err:FOCH0001, Codepoint not valid.

Raised by fn:codepoints-to-string if the input contains an integer that is not the codepoint of a permitted character.

err:FOCH0002, Unsupported collation.

Raised by any function that uses a collation if the requested collation is not recognized.

err:FOCH0003, Unsupported normalization form.

Raised by fn:normalize-unicode if the requested normalization form is not supported by the implementation.

err:FOCH0004, Collation does not support collation units.

Raised by functions such as fn:contains if the requested collation does not operate on a character-by-character basis.

err:FOCH0005, Unrecognized or invalid character name.

Raised by fn:char if the supplied character name is not recognized, or if it represents a codepoint that is not a permitted character.

err:FOCV0001, CSV field quoting error.

Raised when parsing CSV input if a syntax error in the input CSV is found.

err:FOCV0002, Invalid CSV delimiter error.

Raised when parsing CSV input if the field-separator, record-separator, or quote-character option is set to an invalid value.

err:FOCV0003, Duplicate CSV delimiter error.

Raised when parsing CSV input if the same delimiter character is assigned to more than one role.

err:FOCV0004, Argument supplied is not a known column name.

Raised by the function from the get entry of csv-columns-record, if its $key argument is an xs:string and is not one of the known column names.

err:FODC0001, No context document.

Raised by fn:id, fn:idref, and fn:element-with-id if the node that identifies the tree to be searched is a node in a tree whose root is not a document node.

err:FODC0002, Error retrieving resource.

Raised by fn:doc, fn:collection, and fn:uri-collection to indicate that either the supplied URI cannot be dereferenced to obtain a resource, or the resource that is returned is not parseable as XML.

err:FODC0003, Function not defined as deterministic.

Raised by fn:doc, fn:collection, and fn:uri-collection to indicate that it is not possible to return a result that is guaranteed deterministic.

err:FODC0004, Invalid collection URI.

Raised by fn:collection and fn:uri-collection if the argument is not a valid xs:anyURI.

err:FODC0005, Invalid URI reference.

Raised (optionally) by fn:doc if the argument is not a valid xs:anyURI.

err:FODC0006, String passed to fn:parse-xml is not a well-formed XML document.

Raised by fn:parse-xml if the supplied string is not a well-formed and namespace-well-formed XML document; or if DTD validation is requested and the document is not valid against its DTD.

err:FODC0007, String passed to fn:parse-xml is not a DTD-valid XML document.

Raised by fn:parse-xml if DTD validation is requested and the supplied string has no DTD or is not valid against the DTD.

err:FODC0008, Invalid value for the xsd-validation option of fn:parse-xml.

Raised when the xsd-validation option to fn:parse-xml is supplied, and the value is not one of the permitted values; for example if the option type Q{U}NNN is used, and Q{U}NNN does not identify a type in the static context.

err:FODC0009, Processor is not schema-aware.

Raised when the xsd-validation option to fn:parse-xml is set to a value other than skip, if the processor is not schema-aware.

err:FODC0010, The processor does not support serialization.

Raised when fn:serialize is called and the processor does not support serialization, in cases where the host language makes serialization an optional feature.

err:FODC0011, String passed to fn:parse-html is not a well-formed HTML document.

Raised by fn:parse-html if the supplied string is not a well-formed HTML document.

err:FODC0013, No validating XML parser available.

Raised when the dtd-validation option to fn:parse-xml is set, if no validating XML parser is available. Note: it is recommended that all processors should support the dtd-validation option, but there may be environments (such as web browsers) where this is not practically feasible.

err:FODC0014, String passed to fn:parse-xml is not a schema-valid XML document.

Raised by fn:parse-xml if XSD validation is requested and the XML document represented by the supplied string is not valid against the relevant XSD schema.

err:FODC0015, Unable to compile schema for fn:xsd-validator.

Raised by fn:xsd-validator if it is not possible to assemble a valid and consistent schema.

err:FODF1280, Invalid decimal format name.

This error is raised if the decimal format name supplied to fn:format-number is not a valid QName, or if the prefix in the QName is undeclared, or if there is no decimal format in the static context with a matching name.

err:FODF1290, Invalid decimal format property.

This error is raised if a decimal format value supplied to fn:format-number is not valid for the associated property, or if the properties of the decimal format resulting from a supplied map do not have distinct values.

err:FODF1310, Invalid decimal format picture string.

This error is raised if the picture string supplied to fn:format-number or fn:format-integer has invalid syntax.

err:FODT0001, Overflow/underflow in date/time operation.

Raised when casting to date/time datatypes, or performing arithmetic with date/time values, if arithmetic overflow or underflow occurs.

err:FODT0002, Overflow/underflow in duration operation.

Raised when casting to duration datatypes, or performing arithmetic with duration values, if arithmetic overflow or underflow occurs.

err:FODT0003, Invalid timezone value.

Raised by adjust-date-to-timezone and related functions if the supplied timezone is invalid.

err:FODT0004, No timezone data available

Raised by civil-timezone if no timezone data is available for the given date/time and place.

err:FOER0000, Unidentified error.

Error code used by fn:error when no other error code is provided.

err:FOFD1340, Invalid date/time formatting parameters.

This error is raised if the picture string or calendar supplied to fn:format-date, fn:format-time, or fn:format-dateTime has invalid syntax.

err:FOFD1350, Invalid date/time formatting component.

This error is raised if the picture string supplied to fn:format-date selects a component that is not present in a date, or if the picture string supplied to fn:format-time selects a component that is not present in a time.

err:FOGR0001, Attempt to access the value of a generator that is not initialized.

A dynamic error is raised if the code attempts to access the current value of a generator whose initialized field is false().

err:FOGR0002, Attempt to access a value beyond the end of a generator.

A dynamic error is raised if the code attempts to access the current value or move to the next state of a generator whose end-reached field is true().

err:FOHA0001, Invalid algorithm.

Raised by fn:hash if the effective value of the supplied algorithm is not one of the values supported by the implementation.

err:FOJS0001, JSON syntax error.

Raised by functions such as fn:json-doc, fn:parse-json or fn:json-to-xml if the string supplied as input does not conform to the JSON grammar (optionally with implementation-defined extensions).

err:FOJS0003, JSON duplicate keys.

Raised by functions such as map:merge, fn:json-doc, fn:parse-json or fn:json-to-xml if the input contains duplicate keys, when the chosen policy is to reject duplicates.

err:FOJS0004, JSON: not schema-aware.

Raised by fn:json-to-xml if validation is requested when the processor does not support schema validation or typed nodes.

err:FOJS0005, Invalid options.

Raised by functions such as map:merge, fn:parse-json, and fn:xml-to-json if the $options map contains an invalid entry.

err:FOJS0006, Invalid XML representation of JSON.

Raised by fn:xml-to-json if the XML input does not conform to the rules for the XML representation of JSON.

err:FOJS0007, Bad JSON escape sequence.

Raised by fn:xml-to-json if the XML input uses the attribute escaped="true" or escaped-key="true", and the corresponding string or key contains an invalid JSON escape sequence.

err:FOJS0008, Cannot convert element to map.

Raised by fn:element-to-map if the layout selected for converting elements of a given name is unsuitable for an element node with that name, or if the conversion plan explicitly defines the processing of a particular element as an error.

err:FONS0004, No namespace found for prefix.

Raised by fn:resolve-QName and analogous functions if a supplied QName has a prefix that has no binding to a namespace.

err:FONS0005, Base-uri not defined in the static context.

Raised by fn:resolve-uri if no base URI is available for resolving a relative URI.

err:FOPA0001, Origin node is not an ancestor of the target node.

Raised by fn:path if the node supplied in the origin option is not an ancestor of the $node whose relative path is required.

err:FOQM0001, Module URI is a zero-length string.

Raised by fn:load-xquery-module if the supplied module URI is zero-length.

err:FOQM0002, Module URI not found.

Raised by fn:load-xquery-module if no module can be found with the supplied module URI.

err:FOQM0003, Static error in dynamically loaded XQuery module.

Raised by fn:load-xquery-module if a static error (including a statically detected type error) is encountered when processing the library module.

err:FOQM0005, Parameter for dynamically loaded XQuery module has incorrect type.

Raised by fn:load-xquery-module if a value is supplied for the initial context item or for an external variable, and the value does not conform to the required type declared in the dynamically loaded module.

err:FOQM0006, No suitable XQuery processor available.

Raised by fn:load-xquery-module if no XQuery processor is available supporting the requested XQuery version (or if none is available at all).

err:FORG0001, Invalid value for cast/constructor.

A general-purpose error raised when casting, if a cast between two datatypes is allowed in principle, but the supplied value cannot be converted: for example when attempting to cast the string "nine" to an integer.

err:FORG0002, Invalid argument to fn:resolve-uri.

Raised when either argument to fn:resolve-uri is not a valid URI/IRI.

err:FORG0003, fn:zero-or-one called with a sequence containing more than one item.

Raised by fn:zero-or-one if the supplied value contains more than one item.

err:FORG0004, fn:one-or-more called with a sequence containing no items.

Raised by fn:one-or-more if the supplied value is an empty sequence.

err:FORG0005, fn:exactly-one called with a sequence containing zero or more than one item.

Raised by fn:exactly-one if the supplied value is not a singleton sequence.

err:FORG0006, Invalid argument type.

Raised by functions such as fn:max, fn:min, fn:avg, fn:sum if the supplied sequence contains values inappropriate to this function.

err:FORG0008, The two arguments to fn:dateTime have inconsistent timezones.

Raised by fn:dateTime if the two arguments both have timezones and the timezones are different.

err:FORG0009, Error in resolving a relative URI against a base URI in fn:resolve-uri.

A catch-all error for fn:resolve-uri, recognizing that the implementation can choose between a variety of algorithms and that some of these may fail for a variety of reasons.

err:FORG0010, Invalid date/time.

Raised when the input to fn:parse-ietf-date does not match the prescribed grammar, or when it represents an invalid date/time such as 31 February.

err:FORG0011, Invalid radix.

Raised when the radix supplied to fn:parse-integer is not in the range 2 to 36.

err:FORG0012, Invalid digits.

Raised when the digits in the string supplied to fn:parse-integer are not in the range appropriate to the chosen radix.

err:FORX0001, Invalid regular expression flags.

Raised by regular expression functions such as fn:matches and fn:replace if the regular expression flags contain a character other than i, m, q, s, or x.

err:FORX0002, Invalid regular expression.

Raised by regular expression functions such as fn:matches and fn:replace if the regular expression is syntactically invalid.

err:FORX0004, Invalid replacement string.

Raised by fn:replace to report errors in the replacement string.

err:FORX0005, Incompatible arguments for fn:replace.

Raised by fn:replace if both the $replacement and $action arguments are supplied.

err:FOTY0012, Argument to fn:data contains a node that does not have a typed value.

Raised by fn:data, or by implicit atomization, if applied to a node with no typed value, the main example being an element validated against a complex type that defines it to have element-only content.

err:FOTY0013, The argument to fn:data contains a function item.

Raised by fn:data, or by implicit atomization, if the sequence to be atomized contains a function item other than an array.

err:FOTY0014, The argument to fn:string is a function item.

Raised by fn:string, or by implicit string conversion, if the input sequence contains a function item.

err:FOUR0001, Invalid IPv6/IPvFuture authority

A dynamic error is raised if the authority component of a URI contains an open square bracket but no corresponding close square bracket.

err:FOUT1170, Invalid URI reference.

Raised by fn:unparsed-text or fn:unparsed-text-lines if the $source argument contains a fragment identifier, or if it cannot be resolved to an absolute URI (for example, because the base-URI property in the static context is absent), or if it cannot be used to retrieve the string representation of a resource.

err:FOUT1190, Cannot decode external resource.

Raised by fn:unparsed-text or fn:unparsed-text-lines if the $encoding argument is not a valid encoding name, if the processor does not support the specified encoding, if the string representation of the retrieved resource contains octets that cannot be decoded into Unicode characters using the specified encoding, or if the resulting characters are not permitted characters.

err:FOUT1200, Cannot infer encoding of external resource.

Raised by fn:unparsed-text or fn:unparsed-text-lines if the $encoding argument is absent and the processor cannot infer the encoding using external information and the encoding is not UTF-8.

err:FOXT0001, No suitable XSLT processor available

A dynamic error is raised if no XSLT processor suitable for evaluating a call on fn:transform is available.

err:FOXT0002, Invalid parameters to XSLT transformation

A dynamic error is raised if the parameters supplied to fn:transform are invalid, for example if two mutually exclusive parameters are supplied. If a suitable XSLT error code is available (for example in the case where the requested initial-template does not exist in the stylesheet), that error code should be used in preference.

err:FOXT0003, XSLT transformation failed

A dynamic error is raised if an XSLT transformation invoked using fn:transform fails with a static or dynamic error. The XSLT error code is used if available; this error code provides a fallback when no XSLT error code is returned, for example because the processor is an XSLT 1.0 processor.

err:FOXT0004, XSLT transformation has been disabled

A dynamic error is raised if the fn:transform function is invoked when XSLT transformation (or a specific transformation option) has been disabled for security or other reasons.

err:FOXT0006, XSLT output contains non-accepted characters

A dynamic error is raised if the result of the fn:transform function contains characters available only in XML 1.1 and the calling processor cannot handle such characters.

C Built-in named record types

Changes in 4.0 (next | previous)

  1. Named record types used in the signatures of built-in functions are now available as standard in the static context.   [Issue 835 PR 1991 11 May 2025]

This appendix lists the named record types that are used in function signatures in this function library, and that are available in the static context of every application.

These definitions are all in the standard function namespace http://www.w3.org/2005/xpath-functions, which is normally bound to the prefix fn. Because this will not usually be the default namespace for types, the names will usually be written with the prefix fn.

E Glossary (Non-Normative)

atomic item

An atomic item is a pair (T, D) where T (the type annotation) is an atomic type, and D (the datum) is a point in the value space of T.

capturing subexpression

A left parenthesis is recognized as a capturing left parenthesis provided it is not immediately followed by ? or * (see below), is not within a character group (square brackets), and is not escaped with a backslash. The sub-expression enclosed by a capturing left parenthesis and its matching right parenthesis is referred to as a capturing subexpression.

character

A character is an instance of the CharXML production of [Extensible Markup Language (XML) 1.0 (Fifth Edition)].

character position

A string of length N has N+1character positions: one immediately before each character in the string, and one after the last character. In interfaces where character positions are exposed, they are numbered from 1 to N+1.

codepoint

A codepoint is an integer assigned to a character by the Unicode consortium, or reserved for future assignment to a character.

collation

A collation is an algorithm that determines, for any two given strings S1 and S2, whether S1 is less than, equal to, or greater than S2. In this specification, a collation is identified by an absolute URI.

collation unit

The term collation unit as used in this specification is equivalent to the term collation element used in [UTS #10].

context-dependent

A function definitionXP may have the property of being context-dependent: the result of such a function depends on the values of properties in the static and dynamic evaluation context of the caller as well as on the actual supplied arguments (if any). A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

context-independent

A function definitionXP that is not context-dependent is called context-independent.

contextually equal

Two atomic items A and B are said to be contextually equal if the function call fn:compare(A, B) returns zero when evaluated with a specified or context-determined collation and implicit timezone.

CSV

The term comma separated values or CSV refers to a wide variety of plain-text tabular data formats with fields and records separated by standard character delimiters (often, but not invariably, commas).

date formatting function

The three functions fn:format-dateTime, fn:format-date, and fn:format-time are referred to collectively as the date formatting functions.

datum

The datum of an atomic item is a point in the value space of its type, which is also a point in the value space of the primitive type from which that type is derived.

deterministic

A function that is guaranteed to produce identical results from repeated calls within a single execution scope if the explicit and implicit arguments are identical is referred to as deterministic.

digit family

The decimal digit family of a decimal format is the sequence of ten digits with consecutive Unicode codepoints starting with the character that is the value of the zero-digitXP31 property.

disjoint matching segments

The disjoint matching segments obtained by applying a regular expression R to a string S in the presence of a set of flags F are the segments of S that match R (using flags F), after elimination of overlapping segments.

end position

The end position of a segment is the start position of the segment plus its length.

execution scope

An execution scope is a sequence of calls to the function library during which certain aspects of the state are required to remain invariant. For example, two calls to fn:current-dateTime within the same execution scope will return the same result. The execution scope is defined by the host language that invokes the function library.

expanded-QName

An expanded-QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XQuery and XPath Data Model (XDM) 4.0]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.

focus-dependent

A function is focus-dependent if its result depends on the focusXP31 (that is, the context item, position, or size) of the caller.

focus-dependent

A function that is not focus-dependent is called focus-independent.

generator-collection-data-source

An XPath collection or just collection has nothing to do with the f:collection function. An XPath collection can be a sequence, an array or a map.

generator-empty

A generator is empty if and only if its field end-reached has the effective boolean value true(). An empty generator-instance reached in the chain produced by successive evaluations of the move-next method signifies that the yield of a starting generator-instance has been fully traversed. It has the following properties:

  1. get-current's evaluation raises an error.

  2. move-next's evaluation raises an error.

Note:

Empty generators may arise in two ways:

  1. Produced by the function gn:empty-generator.

  2. Termination of a chain of generator instances - the final value of repeated application of the move-next method is an empty generator instance.

    Generators with infinite yield never reach an empty-generator instance in this process.

generator-instance

Generator instance - a given instance of the f:generator record or the result produced by a chain of one or more applications of the move-next method starting from a given f:generator instance.

generator-next-value

The term the next value of a generator denotes the value returned from the get-current() method applied on the generator-instance produced by the move-next() method, if the end-reached field of this next generator-instance is false(). This is also the next value in the generator's yield - see below.

generator-value

Generator value - a "value" produced by a call to the generator method get-current can be either an individual XPath item() or an XPath sequence.

generator-yield

The term yield (of a generator) denotes the consecutive values returned from calling the move-next() and then the get-current method starting from the current generator instance, and on each generator instance thus produced, by applying the move-next() method and then the get-current method until move-next() produces a generator instance whose end-reached field is true().

Note:

  1. Thus, if the consecutive generator instances produced by continuously applying the move-next() method on each of them, starting from the initialized $G1 generator is:

    $G2, $G3, ... , $Gn, ..., then the yield of the generator $G1 is exactly these consecutive generator values:

    $G1 =?> get-current(), $G2 =?> get-current(), ..., $Gn =?> get-current(), ...

  2. If the sequence of the generator instances thus produced is finite (for the final produced generator $Gm, $Gm?end-reached eq true(), then the yield is:

    $G1 =?> get-current(), $G2 =?> get-current(), ..., $Gm-1 =?> get-current()

  3. If the $G1 generator is not initialized ($G1?initialized eq false()), then the yield of this generator is the same as the yield of the (first initialized in the chain) $G2 generator:

    $G2 =?> get-current(), $G3 =?> get-current(), ..., $Gn =?> get-current(), ...

  4. The yield is empty, if $G1?end-reached eq true and the yield is infinite if neither $G1?end-reached eq true() nor any of the consecutive applications of move-next produces a generator $Gx, such that $Gx?end-reached eq true().

Gregorian

The eight primitive types xs:dateTime, xs:date, xs:time, xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gMonth, xs:gDay are referred to collectively as the Gregorian types.

higher-order

Functions that accept functions among their arguments, or that return functions in their result, are described in this specification as higher-order functions.

identical

Two values $V1 and $V2 are defined to be identical if they contain the same number of items and the items are pairwise identical. Two items are identical if and only if one of the following conditions applies:

implementation-defined

Where behavior is described as implementation-defined, variations between processors are permitted, but a conformant implementation must document the choices it has made.

implementation-dependent

Where behavior is described as implementation-dependent, variations between processors are permitted, and conformant implementations are not required to document the choices they have made.

map

A map consists of a sequence of entries, also known as key-value pairs. Each entry comprises a key which is an arbitrary atomic item, and an arbitrary sequence called the associated value.

match

The term match is used in the sense of definition DS2 from [UTS #10].

minimal match

The term minimal match is used in the sense of definition DS4 from [UTS #10].

nondeterministic

A function that is not deterministic is referred to as nondeterministic.

nondeterministic with respect to ordering

Some functions (such as fn:in-scope-prefixes, fn:load-xquery-module, and fn:unordered) produce result sequences or result maps in an implementation-defined or implementation-dependent order. In such cases two calls with the same arguments are not guaranteed to produce the results in the same order. These functions are said to be nondeterministic with respect to ordering.

optional digit character

The optional digit character is the character that is the value of the digitXP31 property.

option parameter conventions

Functions that take an options parameter adopt common conventions on how the options are used. These are referred to as the option parameter conventions. These rules apply only to functions that explicitly refer to them.

permitted character

A permitted character is one within the repertoire accepted by the implementation.

picture string

The formatting of a number is controlled by a picture string. The picture string is a sequence of characters, in which the characters assigned to the properties decimal-separatorXP31 , exponent-separatorXP31, grouping-separatorXP31, digitXP31, and pattern-separatorXP31 and the members of the decimal digit family, are classified as active characters, and all other characters (including the values of the properties percentXP31 and per-milleXP31) are classified as passive characters.

primitive type

A primitive type is one of the 19 primitive atomic types defined in 3.2 Primitive datatypesXS2 of [XML Schema Part 2: Datatypes Second Edition], or the type xs:untypedAtomic defined in [XQuery and XPath Data Model (XDM) 4.0].

same key

Within a map, no two entries have the same key. Two atomic items K1 and K2 are the same key for this purpose if the function call fn:atomic-equal($K1, $K2) returns true.

segment

A segment of a string S is a sequence of zero or more contiguous characters starting at a given character position within S.

single-entry map

A single-entry map is a map containing a single entry.

string

A string is a sequence of zero or more characters, or equivalently, a value in the value space of the xs:string datatype.

type annotation

The type annotation of an atomic item is the most specific atomic type that it is an instance of (it is also an instance of every type from which that type is derived).

Unicode codepoint collation

The collation URI http://www.w3.org/2005/xpath-functions/collation/codepoint identifies a collation which must be recognized by every implementation: it is referred to as the Unicode codepoint collation (not to be confused with the Unicode collation algorithm).

URI

Within this specification, the term URI refers to Universal Resource Identifiers as defined in [RFC 3986] and extended in [RFC 3987] with a new name IRI. The term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2: Datatypes Second Edition].

variadic

The function fn:concat is defined to be variadic: it accepts any number of arguments. No other function has this property.

H Changes since 3.1 (Non-Normative)

H.1 Summary of Changes

  1. If a section of this specification has been updated since version 3.1, an overview of the changes is provided, along with links to navigate to the next or previous change.

    See 1 Introduction

  2. Sections with significant changes are marked with a ✭ symbol in the table of contents. New functions are indicated by ✚.

    See 1 Introduction

  3. PR 1504 2329 

    New in 4.0

    See 2.1.7 fn:insert-separator

  4. New in 4.0

    See 2.1.10 fn:replicate

  5. New in 4.0

    See 2.1.12 fn:slice

  6. PR 1120 1150 

    A callback function can be supplied for comparing individual items.

    See 2.2.4 fn:deep-equal

  7. Changed in 4.0 to use transitive equality comparisons for numeric values.

    See 2.2.5 fn:distinct-values

  8. PR 614 987 

    New in 4.0

    See 2.2.6 fn:duplicate-values

  9. New in 4.0. Originally proposed under the name fn:uniform

    See 2.4.2 fn:all-equal

  10. New in 4.0. Originally proposed under the name fn:unique

    See 2.4.3 fn:all-different

  11. New in 4.0

    See 2.5.3 fn:every

  12. New in 4.0

    See 2.5.9 fn:highest

  13. New in 4.0

    See 2.5.10 fn:index-where

  14. New in 4.0

    See 2.5.11 fn:lowest

  15. New in 4.0

    See 2.5.15 fn:scan-right

  16. New in 4.0

    See 2.5.16 fn:some

  17. PR 795 2228 

    New in 4.0

    See 2.5.19 fn:sort-with

  18. PR 521 761 

    New in 4.0

    See 2.5.22 fn:transitive-closure

  19. New in 4.0

    See 4.4.5 fn:is-NaN

  20. PR 1260 1275 

    A third argument has been added, providing control over the rounding mode.

    See 4.4.6 fn:round

  21. PR 1049 1151 

    Decimal format parameters can now be supplied directly as a map in the third argument, rather than referencing a format defined in the static context.

    See 4.7.2 fn:format-number

  22. PR 1205 1230 

    New in 4.0

    See 4.8.2 math:e

    See 4.8.8 math:cosh

    See 4.8.15 math:sinh

    See 4.8.18 math:tanh

  23. The 3.1 specification suggested that every value in the result range should have the same chance of being chosen. This has been corrected to say that the distribution should be arithmetically uniform (because there are as many xs:double values between 0.01 and 0.1 as there are between 0.1 and 1.0).

    See 4.9.2 fn:random-number-generator

  24. PR 261 306 993 

    New in 4.0

    See 5.4.1 fn:char

  25. New in 4.0

    See 5.4.2 fn:characters

  26. PR 937 995 1190 

    New in 4.0

    See 5.4.13 fn:hash

  27. PR 215 415  

    New in 4.0

    See 7.6.2 fn:parse-uri

  28. PR 1423 1413 

    New in 4.0

    See 7.6.3 fn:build-uri

  29. New in 4.0

    See 12.2.2 fn:in-scope-namespaces

  30. PR 1620 1886 

    Options are added to customize the form of the output.

    See 12.2.9 fn:path

  31. PR 1547 1551 

    New in 4.0

    See 12.2.11 fn:siblings

  32. PR 969 1134 

    New in 4.0

    See 14.4.6 map:filter

  33. PR 478 515 

    New in 4.0

    See 14.4.12 map:keys-where

  34. PR 1575 1906 

    A new function fn:element-to-map is provided for converting XDM trees to maps suitable for serialization as JSON. Unlike the fn:xml-to-json function retained from 3.1, this can handle arbitrary XML as input.

    See 14.5 Converting elements to maps

  35. New in 4.0

    See 15.2.3 array:empty

  36. PR 968 1295 

    New in 4.0

    See 15.2.13 array:index-of

  37. PR 476 1087 

    New in 4.0

    See 15.2.16 array:items

  38. PR 360 476 

    New in 4.0

    See 15.2.18 array:members

    See 15.2.19 array:of-members

  39. Supplying an empty sequence as the value of an optional argument is equivalent to omitting the argument.

    See 15.2.29 array:subarray

  40. PR 1117 1279 

    The $options parameter has been added.

    See 17.1.6 fn:unparsed-text-lines

  41. PR 259 956 

    A new function is available for processing input data in HTML format.

    See 17.3 Functions on HTML Data

    New in 4.0

    See 17.3.2 fn:parse-html

  42. PR 975 1058 1246 

    An option is provided to control how JSON numbers should be formatted.

    See 17.4.4 fn:parse-json

  43. Additional options are available, as defined by fn:parse-json.

    See 17.4.5 fn:json-doc

  44. PR 533 719 834 1066 

    New in 4.0

    See 17.5.4 fn:csv-to-arrays

    See 17.5.7 fn:parse-csv

  45. PR 533 719 834 1066 1605 

    New in 4.0

    See 17.5.10 fn:csv-to-xml

  46. PR 791 1256 1282 1405 

    New in 4.0

    See 17.6.1 fn:invisible-xml

  47. PR 629 803 

    New in 4.0

    See 21.2.222.2.2 fn:message

  48. PR 533 719 834 

    New functions are available for processing input data in CSV (comma separated values) format.

    See 17.5 Functions on CSV Data

  49. Comparison of mixed numeric types (for example xs:double and xs:decimal) now generally converts both values to xs:decimal.

    See 4.3 Comparing numeric values

  50. PR 289 1901 

    A third argument is added, allowing user control of how absent keys should be handled.

    See 14.4.9 map:get

    A third argument is added, allowing user control of how index-out-of-bounds conditions should be handled.

    See 15.2.11 array:get

  51. A new collation URI is defined for Unicode case-insensitive comparison and ordering.

    See 5.3.5 The Unicode case-insensitive collation

  52. PR 1727 1740 

    It is no longer guaranteed that the new key replaces the existing key.

    See 14.4.14 map:put

  53. The group may remove this function, it is considered at risk.

    See 15.2.18 array:members

    See 15.2.19 array:of-members

  54. PR 173 

    New in 4.0

    See 18.419.4 fn:op

  55. PR 203 

    New in 4.0

    See 14.4.1 map:build

  56. PR 207 

    New in 4.0

    See 10.1.2 fn:parse-QName

    See 10.2.5 fn:expanded-QName

  57. PR 222 

    New in 4.0

    See 2.2.3 fn:contains-subsequence

    See 2.2.7 fn:ends-with-subsequence

    See 2.2.9 fn:starts-with-subsequence

  58. PR 250 

    New in 4.0

    See 2.1.3 fn:foot

    See 2.1.15 fn:trunk

    See 15.2.2 array:build

    See 15.2.8 array:foot

    See 15.2.31 array:trunk

  59. PR 258 

    New in 4.0

    See 15.2.14 array:index-where

  60. PR 313 

    The second argument can now be a sequence of integers.

    See 2.1.9 fn:remove

  61. PR 319 

    New in 4.0. The function replaces the internal op:same-key function in 3.1

    See 2.2.1 fn:atomic-equal

  62. PR 326 

    Higher-order functions are no longer an optional feature.

    See 1.2 Conformance

  63. PR 360 

    New in 4.0

    See 14.4.4 map:entries

  64. PR 419 

    New in 4.0

    See 2.1.8 fn:items-at

  65. PR 434 

    New in 4.0

    See 4.5.2 fn:parse-integer

    The function has been extended to allow output in a radix other than 10, for example in hexadecimal.

    See 4.6.1 fn:format-integer

  66. PR 477 

    New in 4.0

    See 15.2.24 array:slice

  67. PR 482 

    Deleted an inaccurate statement concerning the behavior of NaN.

    See 4.3 Comparing numeric values

  68. PR 507 

    New in 4.0

    See 2.5.13 fn:partition

  69. PR 546 

    It is no longer automatically an error if the input contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted.

    See 5.2.1 fn:codepoints-to-string

    It is no longer automatically an error if the resource (after decoding) contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted.

    See 17.1.5 fn:unparsed-text

    The rules regarding use of non-XML characters in JSON texts have been relaxed.

    See 17.4.3 JSON character repertoire

    See 17.4.4 fn:parse-json

    It is no longer automatically an error if the input contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted.

    See 17.4.5 fn:json-doc

  70. PR 609 

    New in 4.0

    See 15.2.28 array:split

  71. PR 631 

    New in 4.0

    See 7.1 fn:decode-from-uri

  72. PR 662 

    Constructor functions now have a zero-arity form; the first argument defaults to the context item.

    See 2223 Constructor functions

  73. PR 680 

    The case-insensitive collation is now defined normatively within this specification, rather than by reference to the HTML "living specification", which is subject to change. The collation can now be used for ordering comparisons as well as equality comparisons.

    See 5.3.6 The HTML ASCII Case-Insensitive Collation

  74. PR 702 

    The function can now take any number of arguments (previously it had to be two or more), and the arguments can be sequences of strings rather than single strings.

    See 5.4.4 fn:concat

  75. PR 710 

    Changes the function to return a sequence of key-value pairs rather than a map.

    See 13.5 fn:function-annotations

  76. PR 727 

    It has been clarified that loading a module has no effect on the static or dynamic context of the caller.

    See 18.219.2 fn:load-xquery-module

  77. PR 828 

    The $predicate callback function accepts an optional position argument.

    See 2.5.4 fn:filter

    The $action callback function accepts an optional position argument.

    See 2.5.7 fn:for-each

    See 2.5.8 fn:for-each-pair

    The $predicate callback function now accepts an optional position argument.

    See 15.2.4 array:filter

    The $action callback function now accepts an optional position argument.

    See 15.2.9 array:for-each

    See 15.2.10 array:for-each-pair

  78. PR 881 

    The way that fn:min and fn:max compare numeric values of different types has changed. The most noticeable effect is that when these functions are applied to a sequence of xs:integer or xs:decimal values, the result is an xs:integer or xs:decimal, rather than the result of converting this to an xs:float or xs:double.

    See 2.4.5 fn:max

    See 2.4.6 fn:min

  79. PR 901 

    The optional third argument can now be supplied as an empty sequence.

    See 2.1.13 fn:subsequence

    The third argument can now be supplied as an empty sequence.

    See 5.4.6 fn:substring

    The second argument can now be an empty sequence.

    See 6.3.3 fn:tokenize

    The optional second argument can now be supplied as an empty sequence.

    See 7.5 fn:resolve-uri

    The 3rd, 4th, and 5th arguments are now optional; previously the function required either 2 or 5 arguments.

    See 9.8.1 fn:format-dateTime

    See 9.8.2 fn:format-date

    See 9.8.3 fn:format-time

    All three arguments are now optional, and each argument can be set to an empty sequence. Previously if $description was supplied, it could not be empty.

    See 21.1.122.1.1 fn:error

    The $label argument can now be set to an empty sequence. Previously if $label was supplied, it could not be empty.

    See 21.2.122.2.1 fn:trace

  80. PR 905 

    The rule that multiple calls on fn:doc supplying the same absolute URI must return the same document node has been clarified; in particular the rule does not apply if the dynamic context for the two calls requires different processing of the documents (such as schema validation or whitespace stripping).

    See 17.1.1 fn:doc

  81. PR 909 

    The function has been expanded in scope to handle comparison of values other than strings.

    See 2.2.2 fn:compare

  82. PR 924 

    Rules have been added clarifying that users should not be allowed to change the schema for the fn namespace.

    See D Schemas

  83. PR 925 

    The decimal format name can now be supplied as a value of type xs:QName, as an alternative to supplying a lexical QName as an instance of xs:string.

    See 4.7.2 fn:format-number

  84. PR 932 

    The specification now prescribes a minimum precision and range for durations.

    See 8.1.2 Limits and precision

  85. PR 933 

    When comments and processing instructions are ignored, any text nodes either side of the comment or processing instruction are now merged prior to comparison.

    See 2.2.4 fn:deep-equal

  86. PR 940 

    New in 4.0

    See 2.5.20 fn:subsequence-where

  87. PR 953 

    Constructor functions for named record types have been introduced.

    See 22.623.6 Constructor functions for named record types

  88. PR 962 

    New in 4.0

    See 2.5.2 fn:do-until

    See 2.5.23 fn:while-do

  89. PR 969 

    New in 4.0

    See 14.4.3 map:empty

  90. PR 984 

    New in 4.0

    See 8.4.1 fn:seconds

  91. PR 987 

    The order of results is now prescribed; it was previously implementation-dependent.

    See 2.2.5 fn:distinct-values

  92. PR 1022 

    Regular expressions can include comments (starting and ending with #) if the c flag is set.

    See 6.1 Regular expression syntax

    See 6.2 Flags

  93. PR 1028 

    An option is provided to control how the JSON null value should be handled.

    See 17.4.4 fn:parse-json

  94. PR 1032 

    New in 4.0

    See 2.1.17 fn:void

  95. PR 1046 

    New in 4.0

    See 2.5.21 fn:take-while

  96. PR 1059 

    Use of an option keyword that is not defined in the specification and is not known to the implementation now results in a dynamic error; previously it was ignored.

    See 1.7 Options

  97. PR 1068 

    New in 4.0

    See 5.4.3 fn:graphemes

  98. PR 1072 

    The return type is now specified more precisely.

    See 18.219.2 fn:load-xquery-module

  99. PR 1090 

    When casting from a string to a duration or time or dateTime, it is now specified that when there are more digits in the fractional seconds than the implementation is able to retain, excess digits are truncated. Rounding upwards (which could affect the number of minutes or hours in the value) is not permitted.

    See 23.224.2 Casting from xs:string and xs:untypedAtomic

  100. PR 1093 

    New in 4.0

    See 5.3.9 fn:collation

  101. PR 1117 

    The $options parameter has been added.

    See 17.1.5 fn:unparsed-text

    See 17.1.7 fn:unparsed-text-available

  102. PR 1182 

    The $predicate callback function may return an empty sequence (meaning false).

    See 2.5.2 fn:do-until

    See 2.5.3 fn:every

    See 2.5.4 fn:filter

    See 2.5.10 fn:index-where

    See 2.5.16 fn:some

    See 2.5.21 fn:take-while

    See 2.5.23 fn:while-do

    See 14.4.6 map:filter

    See 14.4.12 map:keys-where

    See 15.2.4 array:filter

    See 15.2.14 array:index-where

  103. PR 1191 

    The $options parameter has been added, absorbing the $collation parameter.

    See 2.2.4 fn:deep-equal

    New in 4.0

    See 12.3.1 fn:distinct-ordered-nodes

  104. PR 1250 

    For selected properties including percent and exponent-separator, it is now possible to specify a single-character marker to be used in the picture string, together with a multi-character rendition to be used in the formatted output.

    See 4.7.2 fn:format-number

  105. PR 1257 

    The $options parameter has been added.

    See 17.2.1 fn:parse-xml

    See 17.2.2 fn:parse-xml-fragment

  106. PR 1262 

    New in 4.0

    See 5.3.10 fn:collation-available

  107. PR 1265 

    The constraints on the result of the function have been relaxed.

    See 12.1.2 fn:document-uri

  108. PR 1280 

    As a result of changes to the coercion rules, the number of supplied arguments can be greater than the number required: extra arguments are ignored.

    See 2.5.1 fn:apply

  109. PR 1288 

    Additional error conditions have been defined.

    See 17.2.1 fn:parse-xml

  110. PR 1296 

    New in 4.0

    See 2.5.14 fn:scan-left

  111. PR 1333 

    A new option is provided to allow the content of the loaded module to be supplied as a string.

    See 18.219.2 fn:load-xquery-module

  112. PR 1353 

    An option has been added to suppress the escaping of the solidus (forwards slash) character.

    See 17.4.7 fn:xml-to-json

  113. PR 1358 

    New in 4.0

    See 9.3.2 fn:unix-dateTime

  114. PR 1361 

    The term atomic value has been replaced by atomic item.

    See 1.9 Terminology

  115. PR 1393 

    Changes the function to return a sequence of key-value pairs rather than a map.

    See 13.5 fn:function-annotations

  116. PR 1409 

    This section now uses the term primitive type strictly to refer to the 20 atomic types that are not derived by restriction from another atomic type: that is, the 19 primitive atomic types defined in XSD, plus xs:untypedAtomic. The three types xs:integer, xs:dayTimeDuration, and xs:yearMonthDuration, which have custom casting rules but are not strictly-speaking primitive, are now handled in other subsections.

    See 23.124.1 Casting from primitive types to primitive types

    The rules for conversion of dates and times to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since these deliver exactly the same result as the XPath 3.1 rules.

    See 23.1.2.224.1.2.2 Casting date/time values to xs:string

    The rules for conversion of durations to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since the XSD 1.1 rules deliver exactly the same result as the XPath 3.1 rules.

    See 23.1.2.324.1.2.3 Casting xs:duration values to xs:string

  117. PR 1455 

    Numbers now retain their original lexical form, except for any changes needed to satisfy JSON syntax rules (for example, stripping leading zero digits).

    See 17.4.7 fn:xml-to-json

  118. PR 1473 

    New in 4.0

    See 2.1.5 fn:identity

  119. PR 1481 

    The function has been extended to handle other Gregorian types such as xs:gYearMonth.

    See 9.5.1 fn:year-from-dateTime

    See 9.5.2 fn:month-from-dateTime

    The function has been extended to handle other Gregorian types such as xs:gMonthDay.

    See 9.5.3 fn:day-from-dateTime

    The function has been extended to handle other types including xs:time.

    See 9.5.4 fn:hours-from-dateTime

    See 9.5.5 fn:minutes-from-dateTime

    The function has been extended to handle other types such as xs:gYearMonth.

    See 9.5.7 fn:timezone-from-dateTime

  120. PR 1523 

    New functions are provided to obtain information about built-in types and types defined in an imported schema.

    See 1920 Processing types

    New in 4.0

    See 19.1.220.1.2 fn:schema-type

    See 19.1.420.1.4 fn:atomic-type-annotation

    See 19.1.520.1.5 fn:node-type-annotation

  121. PR 1545 

    New in 4.0

    See 9.6.4 fn:civil-timezone

  122. PR 1565 

    The default for the escape option has been changed to false. The 3.1 specification gave the default value as true, but this appears to have been an error, since it was inconsistent with examples given in the specification and with tests in the test suite.

    See 17.4.4 fn:parse-json

  123. PR 1570 

    New in 4.0

    See 19.1.320.1.3 fn:type-of

  124. PR 1587 

    New in 4.0

    See 17.1.8 fn:unparsed-binary

  125. PR 1611 

    The spec has been corrected to note that the function depends on the implicit timezone.

    See 2.2.2 fn:compare

  126. PR 1671 

    New in 4.0.

    See 4.4.3 fn:divide-decimals

  127. PR 1687 

    New in 4.0

    See 14.4.10 map:items

  128. PR 1703 

    Ordered maps are introduced.

    See 14.1 Ordering of Maps

    Enhanced to allow for ordered maps.

    See 14.4.6 map:filter

    See 14.4.7 map:find

    See 14.4.8 map:for-each

    See 14.4.14 map:put

    See 14.4.15 map:remove

    The order of entries in maps is retained.

    See 17.4.4 fn:parse-json

  129. PR 1711 

    It is explicitly stated that the limits for $precision are implementation-defined.

    See 4.4.6 fn:round

    See 4.4.7 fn:round-half-to-even

  130. PR 1727 

    For consistency with the new function map:build, the handling of duplicates may now be controlled by supplying a user-defined callback function as an alternative to the fixed values for the earlier duplicates option.

    See 14.4.13 map:merge

  131. PR 1734 

    In 3.1, given a mixed input sequence such as (1, 3, 4.2e0), the specification was unclear whether it was permitted to add the first two integer items using integer arithmetic, rather than converting all items to doubles before performing any arithmetic. The 4.0 specification is clear that this is permitted; but since the items can be reordered before being added, this is not required.

    See 2.4.4 fn:avg

    See 2.4.7 fn:sum

  132. PR 1825 

    New in 4.0

    See 2.5.12 fn:partial-apply

  133. PR 1856 

    Word boundaries can be matched. Lookahead and lookbehind assertions are supported. Assertions (including ^ and $) can no longer be followed by a quantifier.

    See 6.1 Regular expression syntax

    The output of the function is extended to allow the represention of captured groups found within lookahead assertions.

    See 6.3.4 fn:analyze-string

  134. PR 1879 

    Additional options to control DTD and XInclude processing have been added.

    See 17.2.1 fn:parse-xml

  135. PR 1897 

    The $replacement argument can now be a function that computes the replacement strings.

    See 6.3.2 fn:replace

  136. PR 1906 

    New in 4.0

    See 14.5.10 fn:element-to-map-plan

    New in 4.0.

    See 14.5.11 fn:element-to-map

  137. PR 1910 

    An $options parameter is added. Note that the rules for the $options parameter control aspects of processing that were implementation-defined in earlier versions of this specification. An implementation may provide configuration options designed to retain backwards-compatible behavior when no explicit options are supplied.

    See 17.1.1 fn:doc

    See 17.1.2 fn:doc-available

  138. PR 1913 

    It is now permitted for the regular expression to match a zero-length string.

    See 6.3.2 fn:replace

    See 6.3.3 fn:tokenize

    See 6.3.4 fn:analyze-string

  139. PR 1933 

    New in 4.0

    See 17.2.5 fn:xsd-validator

  140. PR 1991 

    Named record types used in the signatures of built-in functions are now available as standard in the static context.

    See C Built-in named record types

  141. PR 2001 

    New in 4.0.

    See 2.5.18 fn:sort-by

    See 15.2.26 array:sort-by

  142. PR 2013 

    Support for binary input has been added.

    See 17.2.1 fn:parse-xml

    See 17.2.2 fn:parse-xml-fragment

    New in 4.0

    See 17.3.3 fn:html-doc

    See 17.5.8 fn:csv-doc

  143. PR 2030 

    This description of the XSD validation process was previously found (with some duplication) in the XQuery and XSLT specifications; those specifications now reference this description. As a side-effects, the descriptions of the process in XQuery and XSLT are better aligned.

    See 17.2.4 XSD validation

  144. PR 2031 

    Introduced the concept of JNodes.

    See 16 Processing JNodes

    New in 4.0

    See 16.1.1 fn:jtree

    See 16.1.3 fn:jnode-selector

    See 16.1.4 fn:jnode-position

  145. PR 2149 

    Generalized to work with JNodes as well as XNodes.

    See 12.2.1 fn:has-children

    The function is extended to handle JNodes.

    See 12.2.9 fn:path

    Generalized to work with JNodes as well as XNodes.

    See 12.3.2 fn:innermost

    See 12.3.3 fn:outermost

  146. PR 2168 

    Atomic items of types xs:hexBinary and xs:base64Binary are now mutually comparable. In rare cases, where an application uses both types and assumes they are distinct, this can represent a backwards incompatibility.

    See 2.2.1 fn:atomic-equal

    See 2.2.4 fn:deep-equal

    See 2.2.5 fn:distinct-values

  147. PR 2223 

    An error may now be raised if the base URI is not a valid LEIRI reference.

    See 12.1.1 fn:base-uri

  148. PR 2224 

    The $action callback function now accepts an optional position argument.

    See 14.4.6 map:filter

    See 14.4.8 map:for-each

  149. PR 2228 

    New in 4.0

    See 15.2.27 array:sort-with

  150. PR 2249 

    The specification now describes in more detail how to determine the effective encoding value.

    See 17.1.5 fn:unparsed-text

  151. PR 2256 

    In the interests of consistency, the index-of function now defines equality to mean contextually equal. This has the implication that NaN is now considered equal to NaN.

    See 2.2.8 fn:index-of

  152. PR 2259 

    A new parameter canonical is available to give control over serialization of XML, XHTML, and JSON.

    See 17.2.3 fn:serialize

  153. PR 2286 

    The type of $value has been generalized to xs:anyAtomicType?.

    See 5.4.7 fn:string-length

    See 5.4.8 fn:normalize-space

  154. PR 2387 

    It is now recommended that out-of-range xs:double values should translate to positive or negative infinity.

    See 17.4.4 fn:parse-json