Please check the errata for any errors or issues reported since publication.
See also translations.
This document is also available in these non-normative formats: XML.
Copyright © 2000 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
XPath 4.0 is an expression language that allows the processing of values conforming to the data model defined in [XQuery and XPath Data Model (XDM) 4.0]. The name of the language derives from its most distinctive feature, the path expression, which provides a means of hierarchic addressing of the nodes in an XML tree. As well as modeling the tree structure of XML, the data model also includes atomic items, function items, maps, arrays, and sequences. This version of XPath supports JSON as well as XML, and adds many new functions in [XQuery and XPath Functions and Operators 4.0].
XPath 4.0 is a superset of XPath 3.1. A detailed list of changes made since XPath 3.1 can be found in I Change Log.
This is a draft prepared by the QT4CG (officially registered in W3C as the XSLT Extensions Community Group). Comments are invited.
The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).
Michael was central to the development of XML and many related technologies. He brought a polymathic breadth of knowledge and experience to everything he did. This, combined with his indefatigable curiosity and appetite for learning, made him an invaluable contributor to our project, along with many others. We have lost a brilliant thinker, a patient teacher, and a loyal friend.
As noted in 2.1.2 Values, every value in XPath 4.0 is regarded as a sequence of zero, one, or more items. The type system of XPath 4.0, described in this section, classifies the kinds of value that the language can handle, and the operations permitted on different kinds of value.
The type system of XPath 4.0 is related to the type system of [XML Schema 1.0] or [XML Schema 1.1] in two ways:
atomic items in XPath 4.0 (which are one kind of item) have atomic types such as xs:string, xs:boolean, and xs:integer. These types are taken directly from their definitions in [XML Schema 1.0] or [XML Schema 1.1].
Nodes (which are another kind of item) have a property called a type annotation which determines the type of their content. The type annotation is a schema type. The type annotation of a node must not be confused with the item type of the node. For example, an element <age>23</age> might have been validated against a schema that defines this element as having xs:integer content. If this is the case, the type annotation of the node will be xs:integer, and in the XPath 4.0 type system, the node will match the item typeelement(age, xs:integer).
This chapter of the specification starts by defining sequence types and item types, which describe the range of values that can be bound to variables, used in expressions, or passed to functions. It then describes how these relate to schema types, that is, the simple and complex types defined in an XSD schema.
Note:
In many situations the terms item type and sequence type are used interchangeably to refer either to the type itself, or to the syntactic construct that designates the type: so in the expression $x instance of xs:string*, the construct xs:string* uses the SequenceType syntax to designate a sequence type whose instances are sequences of strings. When more precision is required, the specification is careful to use the terms item type and sequence type to refer to the actual types, while using the production names ItemType and SequenceType to refer to the syntactic designators of these types.
The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules". [ PR 254 29 November 2022]
The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger. [Issue 117 PR 254 29 November 2022]
The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:double. [Issue 980 PR 911 30 January 2024]
The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary. [Issues 130 480 PR 815 7 November 2023]
The coercion rules now apply recursively to the members of an array and the entries in a map. [Issue 1318 PR 1501]
The coercion rules now reorder the entries in a map when the required type is a record type. [Issue 1862 ]
[Definition: The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter. ] The required type is expressed as a sequence type. The effect of the coercion rules may be to accept the value as supplied, to convert it to a value that matches the required type, or to reject it with a type error.
This section defines how the coercion rules operate; the situations in which the rules apply are defined elsewhere, by reference to this section.
Note:
In previous versions of this specification, the coercion rules were referred to as the function conversion rules. The terminology has changed because the rules are not exclusively associated with functions or function calling.
If the required type is empty-sequence(), no coercion takes place (the supplied value must be an empty sequence, or a type error occurs).
In all other cases, the required sequence typeT comprises a required item typeR and an optional occurrence indicator. The coercion rules are then applied to a supplied value V and the required type T as follows:
If XPath 1.0 compatibility mode is true and V is not an instance of the required type T, then the conversions defined in 3.4.1 XPath 1.0 Compatibility Rules are applied to V. Then:
Each item in V is processed against the required item type R using the item coercion rules defined in 3.4.2 Item Coercion Rules, and the results are sequence-concatenated into a single sequence V′.
A type error is raised if the cardinality of V′ does not match the required cardinality of T [err:XPTY0004].
Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.
It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item. [Issue 1020 PRs 1023 1128 9 April 2024]
Function coercion is a transformation applied to function items during application of the coercion rules. [Definition: Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.]
Given a function F, and an expected function type T, function coercion proceeds as follows:
If F has higher arity than T, a type error is raised [err:XPTY0004]
If F has lower arity than T, then F is wrapped in a new function that declares and ignores the additional argument; the following steps are then applied to this new function.
For example, if T is function(node(), xs:boolean) as xs:string, and the supplied function is fn:name#1, then the supplied function is effectively replaced by function($n as node(), $b as xs:boolean) as xs:string { fn:name($n) }
Note:
This mechanism makes it easier to design versatile and extensible higher-order functions. For example, in previous versions of this specification, the second argument of the fn:filter function expected an argument of type function(item()) as xs:boolean. This has now been extended to function(item(), xs:integer) as xs:boolean, but existing code continues to work, because callback functions that are not interested in the value of the second argument simply ignore it.
A type error is raised [err:XPTY0004] if, for any parameter type, or for the result type, the relevant type in the signature of the supplied function and the relevant type in the expected function type are substantively disjoint.
For example, the types xs:integer and xs:string are substantively disjoint, so a function with signature function(xs:integer) as xs:boolean cannot be supplied where the expected type is function(xs:string) as xs:boolean.
Function coercion then returns a new function item with the following properties (as defined in Section 7.1 Function ItemsDM):
name: The name of F(if not absent).
identity: A new function identity distinct from the identity of any other function item.
Note:
See also 4.5.7 Function Identity.
parameter names: The parameter names of F.
signature: Annotations is set to the annotations of F. TypedFunctionType is set to the expected type.
implementation: In effect, a FunctionBody that calls F, passing it the parameters of this new function, in order.
nonlocal variable bindings: An empty mapping.
These rules have the following consequences:
SequenceType matching of the function’s arguments and result are delayed until that function is called.
When the coerced function is called, the supplied arguments must match the parameter typed defined in T; it is not sufficient to match the parameter types defined in F.
The coercion rules rules applied to the function’s arguments and result are defined by the SequenceType it has most recently been coerced to. Additional coercion rules could apply when the wrapped function is called.
If an implementation has static type information about a function, that can be used to type check the function’s argument and return types during static analysis.
When function coercion is applied to a map or an array, the resulting function is not a map or array, and cannot be used as such. For example, the expression
let $f as function(xs:integer) as xs:boolean := { 0: false(), 1: true() }
return $f?0raises a type error, because a lookup expression requires the left hand operand to be a map or array, and $f is neither.
When function types are used as alternatives in a choice item type, the supplied function is coerced to the first alternative for which coercion does not raise a type error. In this situation it is important to write the alternatives in order, with the most specific first.
Note:
The semantics of function coercion are specified in terms of wrapping the functions. Static typing may be able to reduce the number of places where this is actually necessary. However, it cannot be assumed that because a supplied function is an instance of the required function type, no function coercion is necessary: the supplied function might not perform all required checks on the types of its arguments.
Since maps and arrays are also functions in XPath 4.0, function coercion applies to them as well. For instance, consider the following expression:
let $m := {
"Monday" : true(),
"Wednesday" : false(),
"Friday" : true()
}
let $days := ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
return filter($days, $m) The map $m is an instance of function(xs:anyAtomicType?) as item()*. When the fn:filter() function is called, the following occurs to the map:
The map $m is treated as a function equivalent to map:get($m, ?).
The coercion rules result in applying function coercion to this function, wrapping it in a new function (M′) with the signature function(item(), xs:integer) as xs:boolean.
When M′ is called by fn:filter(), coercion and SequenceType matching rules are applied to the argument, resulting in an item() value ($a) or a type error.
The function map:get($m, ?) is called with $a as the argument; this returns either an xs:boolean or the empty sequence (call the result R).
The wrapper function $p applies the coercion rules to R. If R is an xs:boolean the matching succeeds. When it is an empty sequence (in particular, $m does not contain a key for "Tuesday"), a type error is raised [err:XPTY0004], since the expected type is xs:boolean and the actual type is an empty sequence.
Consider the following expression:
let $m := {
"Monday" : true(),
"Wednesday" : false(),
"Friday" : true(),
}
let $days := ("Monday", "Wednesday", "Friday")
return filter($days, $m)In this case the result of the expression is the sequence ("Monday", "Friday"). But if the input sequence included the string "Tuesday", the filter operation would fail with a type error.
Note:
Function coercion applies even if the supplied function matches the required type.
For example, consider this case:
declare function local:filter(
$s as item()*,
$p as function(xs:string) as xs:boolean
) as item()* {
$s[$p(.)]
};
let $f := function($a) { $a mod 2 = 0 }
return local:filter(1 to 10, $f)Here the supplied function $f is an instance of the required type, because its signature defaults the argument type to item()*, which is a supertype of xs:string. The expression $s[$p(.)] could in principle succeed. However, function coercion ensures that the supplied function is wrapped in a function that requires the argument to be of type xs:string, so the call fails with a type error when the wrapping function is invoked supplying an xs:integer as the argument.
This section discusses each of the basic kinds of expression. Each kind of expression has a name such as PathExpr, which is introduced on the left side of the grammar production that defines the expression. Since XPath 4.0 is a composable language, each kind of expression is defined in terms of other expressions whose operators have a higher precedence. In this way, the precedence of operators is represented explicitly in the grammar.
The order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [A XPath 4.0 Grammar].
The highest-level symbol in the XPath grammar is XPath.
XPath | ::= | Expr |
Expr | ::= | (ExprSingle ++ ",") |
ExprSingle | ::= | ForExpr |
ExprSingle | ::= | ForExpr |
ForExpr | ::= | ForClauseForLetReturn |
LetExpr | ::= | LetClauseForLetReturn |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBinding ++ ",") "satisfies" ExprSingle |
IfExpr | ::= | "if" "(" Expr ")" (UnbracedActions | BracedAction) |
OrExpr | ::= | AndExpr ("or" AndExpr)* |
The XPath 4.0 operator that has lowest precedence is the comma operator, which is used to combine two operands to form a sequence. As shown in the grammar, a general expression (Expr) can consist of multiple ExprSingle operands, separated by commas.
The name ExprSingle denotes an expression that does not contain a top-level comma operator (despite its name, an ExprSingle may evaluate to a sequence containing more than one item.)
The symbol ExprSingle is used in various places in the grammar where an expression is not allowed to contain a top-level comma. For example, each of the arguments of a function call must be a ExprSingle, because commas are used to separate the arguments of a function call.
After the comma, the expressions that have next lowest precedence are ForExpr, LetExpr, QuantifiedExpr, IfExpr, and OrExpr. Each of these expressions is described in a separate section of this document.
Functions in XPath 4.0 arise in two ways:
A function definition contains information about a family of functions with the same name and a defined arity range. These functions are in most cases known statically (they appear in the statically known function definitions), but there may be further function definitions that are known only dynamically (appearing in the dynamically known function definitions).
Function items are XDM items that can be called using a dynamic function call. They are values that can be bound to variables, passed as arguments, returned as function results, and generally manipulated in the same way as other XDM values.
The functions defined by a statically known function definition can be invoked using a static function call. Function items corresponding to these definitions can also be obtained, as dynamic values, by evaluating a named function reference. Function items can also be obtained using the fn:function-lookup function: in this case the function name and arity do not need to be known statically, and the function definition need not be present in the static context, so long as it is in the dynamic context.
Static and dynamic function calls are described in the following sections.
[Definition: A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.]
The rules for partial function application in static function calls and dynamic function calls have a great deal in common, but they are stated separately below for clarity.
In each case, the result of a partial function application is a function item, whose arity is equal to the number of placeholders in the call.
More specifically, the result of the partial function application is a partially applied function. [Definition: A partially applied function is a function created by partial function application.]
For static function calls, the result is obtained as follows:
The function definitionFD to be partially applied is determined in the same way as for a static function call without placeholders, as described in 4.5.1.1 Static Function Call Syntax. For this purpose an ArgumentPlaceholder contributes to the count of arguments.
The parameters of FD are classified into three categories:
Parameters that map to a placeholder, referred to as placeholder parameters.
Parameters for which an explicit value is given in the function call (either positionally or by keyword), referred to as explicitly supplied parameters.
Parameters (which are necessarily optional parameters) for which no corresponding argument is supplied, either as a placeholder or with an explicit value. These are referred to as defaulted parameters.
Note:
A partial function application need not have any explicitly supplied parameters. For example, the partial function application fn:string(?) is allowed; it has exactly the same effect as the named function reference fn:string#1.
Explicitly supplied parameters and defaulted parameters are evaluated and converted to the required type using the rules for a static function call. This may result in an error being raised.
A type error is raised if any of the explicitly supplied or defaulted parameters, after applying the coercion rules, does not match the required type of the corresponding parameter.
In addition, a dynamic error may be raised if any of the explicitly supplied or defaulted parameters does not match other constraints on the value of that parameter (for example, if the value supplied for a parameter expecting a regular expression is not a valid regular expression); or if the processor is able to establish that evaluation of the resulting function will fail for any other reason (for example, if an error is raised while evaluating a subexpression in the function body that depends only on explicitly supplied and defaulted parameters).
In all cases the error code is the same as for a static function call supplying the same invalid value(s).
In the particular case where all the supplied arguments are placeholders, the error behavior should be the same as for an equivalent named function reference: for example, fn:id#1 fails if there is no context node, and fn:id(?)should fail likewise.
The result is a partially applied function having the following properties (which are defined in Section 7.1 Function ItemsDM):
name: The name of FD if all parameters map to placeholders, that is, if the partial function application is equivalent to the corresponding named function reference. Otherwise, the name is absent.
identity: A new function identity distinct from the identity of any other function item.
Note:
See also 4.5.7 Function Identity.
arity: The number of placeholders in the function call.
parameter names: The names of the parameters of FD that have been identified as placeholder parameters, retaining the order in which the placeholders appear in the function call.
Note:
A partial function application can be used to change the order of parameters, for example fn:contains(substring := ?, value := ?) returns a function item that is equivalent to fn:contains#2, but with the order of arguments reversed.
signature: The parameters in the returned function are the parameters of FD that have been identified as placeholder parameters, retaining the order in which the placeholders appear in the function call. The result type of the returned function is the same as the result type of FD.
An implementation which can determine a more specific signature (for example, through use of type analysis) is permitted to do so.
annotations: The annotations of FD.
body: The body of FD.
captured context: The static and dynamic context of the function call, augmented, for each explicitly supplied parameter and each defaulted parameter, with a binding of the converted argument value to the corresponding parameter name.
Note:
A partial function application can be used to change the order of parameters, for example fn:contains(substring := ?, value := ?) returns a function item that is equivalent to fn:contains#2, but with the order of arguments reversed.
The following partial function application creates a function item that computes the sum of squares of a sequence.
let $sum-of-squares := fold-right(?, 0, function($a, $b) { $a*$a + $b })
return $sum-of-squares(1 to 3)$sum-of-squares is an anonymous function. It has one parameter, named $seq, which is taken from the corresponding parameter in fn:fold-right (the other two parameters are fixed). The implementation is the implementation of fn:fold-right, which is a context-independent system function. The nonlocal bindings contain the fixed bindings for the second and third parameters of fn:fold-right.
For dynamic function calls, the result is obtained as follows:
The function itemFI to be partially applied is determined in the same way as for a dynamic function call without placeholders, as described in 4.5.3 Dynamic Function Calls. For this purpose an ArgumentPlaceholder contributes to the count of arguments.
The parameters of FI are classified into two categories:
Parameters that map to a placeholder, referred to as placeholder parameters.
Parameters for which an explicit value is given in the function call, referred to as supplied parameters.
Note:
A partial function application need not have any explicitly supplied parameters. For example, if $f is a function with arity 2, then the partial function application $f(?, ?) returns a function that has exactly the same effect as $f.
Arguments corresponding to supplied parameters are evaluated and converted to the required type of the parameter, using the rules for dynamic function calls.
A type error is raised if any of the supplied parameters, after applying the coercion rules, does not match the required type.
In addition, a dynamic error may be raised if any of the supplied parameters does not match other constraints on the value of that parameter (for example, if the value supplied for a parameter expecting a regular expression is not a valid regular expression); or if the processor is able to establish that evaluation of the resulting function will fail for any other reason (for example, if an error is raised while evaluating a subexpression in the function body that depends only on explicitly supplied parameters).
In both cases the error code is the same as for a dynamic function call supplying the same invalid value.
The result of the partial function application is a partially applied function with the following properties (which are defined in Section 7.1 Function ItemsDM):
name: Absent.
arity: The number of placeholders in the function call.
parameter names: The names of parameters in FI that have been identified as placeholder parameters, in order.
Note:
In a dynamic partial function application, argument keywords are not available, so it is not possible to change the order of parameters.
signature: The signature of FI, removing the types of supplied parameters. An implementation which can determine a more specific signature (for example, through use of type analysis) is permitted to do so.
annotations: The annotations of FI.
body: The body of FI.
captured context: the captured context of FI, augmented, for each supplied parameter, with a binding of the converted argument value to the corresponding parameter name.
Note:
In a dynamic partial function application, argument keywords are not available, so it is not possible to change the order of parameters.
In the following example, $f is an anonymous function, and $paf is a partially applied function created from $f.
let $f := function($seq, $delim) { fold-left($seq, "", concat(?, $delim, ?)) }
let $paf := $f(?, ".")
return $paf(1 to 5)$paf is also an anonymous function. It has one parameter, named $delim, which is taken from the corresponding parameter in $f (the other parameter is fixed). The implementation of $paf is the implementation of $f, which is fn:fold-left($seq, "", fn:concat(?, $delim, ?)). This implementation is associated with the SC and DC of the original expression in $f. The nonlocal bindings associate the value "." with the parameter $delim.
Partial function application never returns a map or an array. If $f is a map or an array, then $f(?) is a partial function application that returns a function, but the function it returns is neither a map nor an array.
NamedFunctionRef | ::= | EQName "#" IntegerLiteral |
| /* xgc: reserved-function-names */ | ||
EQName | ::= | QName | URIQualifiedName |
IntegerLiteral | ::= | Digits |
| /* ws: explicit */ | ||
Digits | ::= | DecDigit ((DecDigit | "_")* DecDigit)? |
| /* ws: explicit */ | ||
DecDigit | ::= | [0-9] |
| /* ws: explicit */ |
[Definition: A named function reference is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.]
The name and arity of the required function are known statically.
If the EQName is a lexical QName, it is expanded using the default function namespace in the static context.
The expanded QName and arity must correspond to a function definition present in the static context. More specifically, for a named function reference F#N, there must be a function definition in the statically known function definitions whose name matches F, and whose arity range includes N. Call this function definitionFD.
If FD is context dependent for the given arity, then the returned function item has a captured context comprising the static and dynamic context of the named function reference.
Note:
In practice, it is necessary to retain only those parts of the static and dynamic context that can affect the outcome. These means it is unnecessary to retain parts of the context that no system function depends on (for example, local variables), or parts that are invariant within an execution scope (for example, the implicit timezone).
Consider:
let $f := <foo/>/fn:name#0 return <bar/>/$f()
The function fn:name(), with no arguments, returns the name of the context node. The function item delivered by evaluating the expression fn:name#0 returns the name of the element that was the context node at the point where the function reference was evaluated (that is, the <foo> element). This expression therefore returns "foo", not "bar".
An error is raised if the identified function depends on components of the static or dynamic context that are not present, or that have unsuitable values. For example [err:XPDY0002] is raised for the expression fn:name#0 if the context item is absent, and [err:FODC0001]FO is raised for the call fn:id#1 if the context item is not a node in a tree that is rooted at a document node. The error that is raised is the same as the error that would be raised by the corresponding function if called with the same static and dynamic context.
If the expanded QName and arity in a named function reference do not match the name and arity range of a function definition in the static context, a static error is raised [err:XPST0017].
The value of a NamedFunctionRef is a function itemFI obtained from FD as follows:
name: The name of FD.
identity:
If FD is context dependent for the given arity, then a new function identity distinct from the identity of any other function item.
Note:
In the general case, a function reference to a context-dependent function will produce different results every time it is evaluated, because the resulting function item has a captured context (see Section 7.1 Function ItemsDM) that includes the dynamic context of the particular evaluation. Optimizers, however, are allowed to detect cases where the captured context happens to be the same, or where any variations are immaterial, and where it is therefore safe to return the same function item each time. This might be the case, for example, where the only context dependency of a function is on the default collation, and the default collation for both evaluations is known to be the same.
Otherwise, a function identity that is the same as that produced by the evaluation of any other named function reference with the same function name and arity.
This rule applies even across different execution scopesFO: for example if a parameter to a call to fn:transform is set to the result of the expression fn:abs#1, then the function item passed as the parameter value will be identical to that obtained by evaluating the expression fn:abs#1 within the target XSLT stylesheet.
This rule also applies when the target function definition is nondeterministicFO. For example all evaluations of the named function reference map:keys#2 return identical function items, even though two evaluations of map:keys with the same arguments may produce different results.
Note:
See also 4.5.7 Function Identity.
arity: As specified in the named function reference.
parameter names: The first A parameter names of FD, where A is the required arity.
signature: Formed from the required types of the first A parameters of FD, and the function result type of FD.
annotations: The annotations of FD.
body: The body of FD.
captured context: Comprises the static and dynamic context of the named function reference, augmented with bindings of the names of parameters of FD beyond the A’th parameter, to their respective default values.
Note:
In practice, it is necessary to retain only the parts of the context that the function actually depends on (if any).
Note:
Consider the system function fn:format-date, which has an arity range of 2 to 5. The named function reference fn:format-date#3 returns a function item whose three parameters correspond to the first three parameters of fn:format-date; the remaining two arguments will take their default values. To obtain an arity-3 function that binds to arguments 1, 2, and 5 of fn:format-date, use the partial function application format-date(?, ?, place := ?).
The following are examples of named function references:
fn:abs#1 references the fn:abs function which takes a single argument.
fn:concat#5 references the fn:concat function which takes 5 arguments.
local:myfunc#2 references a function named local:myfunc which takes 2 arguments.
Note:
Function items, as values in the data model, have a fixed arity, and a dynamic function call always supplies the arguments positionally. In effect, the result of evaluating my:func#3 is the same as the result of evaluating the inline function expression fn($x, $y, $z) { my:func($x, $y, $z) }, except that the returned function has a name (it retains the name my:func).
In inline function expressions, the keyword function may be abbreviated as fn. [Issue 1192 PR 1197 21 May 2024]
New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code } [Issue 503 PR 521 30 May 2023]
An inline function may be annotated as a %method, giving it access to its containing map. [Issues 1800 1845 PRs 1817 1853 4 March 2025]
InlineFunctionExpr | ::= | MethodAnnotation* ("function" | "fn") FunctionSignature? FunctionBody |
MethodAnnotation | ::= | "%method" |
FunctionSignature | ::= | "(" ParamList ")" TypeDeclaration? |
ParamList | ::= | (VarNameAndType ** ",") |
VarNameAndType | ::= | "$" EQNameTypeDeclaration? |
EQName | ::= | QName | URIQualifiedName |
TypeDeclaration | ::= | "as" SequenceType |
SequenceType | ::= | ("empty-sequence" "(" ")") |
FunctionBody | ::= | EnclosedExpr |
EnclosedExpr | ::= | "{" Expr? "}" |
[Definition: An inline function expression, when evaluated, creates an anonymous function defined directly in the inline function expression.] An inline function expression specifies the names and SequenceTypes of the parameters to the function, the SequenceType of the result, and the body of the function.
An inline function expression whose FunctionSignature is omitted is known as a focus function. Focus functions are described in 4.5.6.2 Focus Functions.
[Definition: An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.]
The keywords function and fn are synonymous.
The syntax allows the names and types of the function argument to be declared, along with the type of the result:
function($x as xs:integer, $y as xs:integer) as xs:integer { $x + $y }The types can be omitted, and the keyword can be abbreviated:
fn($x, $y) { $x + $y }A zero-arity function can be written as, for example, fn() { current-date() }.
If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted, its default result type is item()*.
The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error [err:XQST0039] for an inline function expression to have more than one parameter with the same name.
The annotation keyword %method is described in 4.5.6.1 Methods.
The static context for the function body is inherited from the location of the inline function expression.
The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope for the inline function expression.
Note:
Function parameter names can mask variables that would otherwise be in scope for the function body.
The result of an inline function expression is a single function item with the following properties (as defined in Section 7.1 Function ItemsDM):
name: Absent.
identity: A new function identity distinct from the identity of any other function item.
Note:
See also 4.5.7 Function Identity.
parameter names: The parameter names in the InlineFunctionExpr’s ParamList.
signature: A FunctionType constructed from the SequenceTypes in the InlineFunctionExpr. An implementation which can determine a more specific signature (for example, through use of type analysis of the function’s body) is permitted to do so.
annotations: If the keyword %method is present, then a list containing a single annotation whose name is a QName with local name "method" and namespace "http://www.w3.org/2012/xquery" and whose value is an empty sequence; otherwise an empty set..
body: The FunctionBody of the InlineFunctionExpr.
captured context: the static context is the static context of the inline function expression. The dynamic context has an absent focus, and a set of variable bindings comprising the variable values component of the dynamic context of the InlineFunctionExpr.
The following are examples of some inline function expressions:
This example creates a function that takes no arguments and returns a sequence of the first 6 primes:
function() as xs:integer+ { 2, 3, 5, 7, 11, 13 }This example creates a function that takes two xs:double arguments and returns their product:
fn($a as xs:double, $b as xs:double) as xs:double { $a * $b }This example creates and invokes a function that captures the value of a local variable in its scope:
let $incrementors := (
for $x in 1 to 10
return function($y) as xs:integer { $x + $y }
)
return $incrementors[2](4)The result of this expression is 6