This article is part of the [[XQuery|XQuery Portal]].It summarizes provides a summary of the new most important features of the [httphttps://www.w3.org/TR/xquery-31/ XQuery 3.1] Working Draftthat are already supported by BaseXRecommendation.
==Maps==
A ''map'' is a function that associates a set of keys with values, resulting in a collection of key/value pairs. Each key/value pair in a map is called an entry. A key is an arbitrary atomic value, and the associated value is an arbitrary sequence. Within a map, no two entries have the same key, when compared using the {{Code|eq}} operator. It is not necessary that all the keys should be mutually comparable (for example, they can include a mixture of integers and strings).
Maps have the following syntaxcan be constructed as follows:
<pre classlang="brush:'xquery"'>(: empty map :)map { }, (: empty map with two entries :)map { 'key': true(), 1984: (<a/>, <b/>) }, (: map with two entries :)map:merge( (: map with ten entries :) for $i in 1 to 10 return map { $i: 'value' || $i })
</pre>
The function corresponding to the map has the signature {{Code|function($key as xs:anyAtomicType) as item()*}}. The expression {{Code|$map($key)}} returns the associated value; the function call {{Code|map:get($map, $key)}} is equivalent. For example, if {{Code|$books-by-isbn}} is a map whose keys are ISBNs and whose associated values are {{Code|book}} elements, then the expression {{Code|$books-by-isbn("0470192747")}} returns the {{Code|book}} element with the given ISBN. The fact that a map is a function item allows it to be passed as an argument to higher[[Higher-order functions Order Functions]] that expect a function item as one of their arguments. As an example, the following query uses the higher-order function {{Code|fn:map($f, $seq)}} to extract all bound values from a map:
<pre classlang="brush:'xquery"'>
let $map := map { 'foo': 42, 'bar': 'baz', 123: 456 }
return fn:for-each(map:keys($map), $map)
This returns some permutation of {{Code|(42, 'baz', 456)}}.
Because a map is a function item, functions that apply to functions also apply to maps. A map is an anonymous function, so {{Code|fn:function-name}} returns the empty sequence; {{Code|fn:function-arity}} always returns {{Code|1}}. Like all other values, maps are immutable. For example, the <code>[[{{Function|Map Module#map:remove|map:remove]]</code> }} function creates a new map by removing an entry from an existing map, but the existing map is not changed by the operation.Like sequences, maps have no identity. It is meaningful to compare the contents of two maps, but there is no way of asking whether they are "the same map": two maps with the same content are indistinguishable. Maps may be compared using the {{Code|fn:deep-equal}} function. The [[Map Module]] describes the available set of map functions. =Arrays= An ''array'' is a function that associates a set of positions, represented as positive integer keys, with values. The first position in an array is associated with the integer {{Code|1}}. The values of an array are called its members. In the type hierarchy, array has a distinct type, which is derived from function. In BaseX, arrays (as well as sequences) are based on an efficient [https://en.wikipedia.org/wiki/Finger_tree Finger Tree] implementation. Arrays can be constructed in two ways. With the square bracket notation, the comma serves as delimiter: <pre lang='xquery'>[], (: empty array :)[ (1, 2) ], (: array with single member :)[ 1 to 2, 3 ] (: array with two members; same as: [ (1, 2), 3 ] :)</pre> With the {{Code|array}} keyword and curly brackets, the inner expression is evaluated as usual, and the resulting values will be the members of the array: <pre lang='xquery'>array { }, (: empty array; same as: array { () } :) array { (1, 2) }, (: array with two members; same as: array { 1, 2 } :)array { 1 to 2, 3 } (: array with three members; same as: array { 1, 2, 3 } :)</pre> The function corresponding to the array has the signature {{Code|function($index as xs:integer) as item()*}}. The expression {{Code|$array($index)}} returns an addressed member of the array. The following query returns the five array members {{Code|48 49 50 51 52}} as result: <pre lang='xquery'>let $array := array { 48 to 52 }for $i in 1 to array:size($array)return $array($i)</pre> Like all other values, arrays are immutable. For example, the {{Function|Array|array:reverse}} function creates a new array containing a re-ordering of the members of an existing array, but the existing array is not changed by the operation. Like sequences, arrays have no identity. It is meaningful to compare the contents of two arrays, but there is no way of asking whether they are "the same array": two arrays with the same content are indistinguishable. ==Atomization== If an array is ''atomized'', all of its members will be atomized. As a result, an atomized item may now result in more than one item. Some examples: <pre lang='xquery'>fn:data([1 to 2]) (: returns the sequence 1, 2 :)[ 'a', 'b', 'c' ] = 'b' (: returns true :)<a>{ [ 1, 2 ] }</a> (: returns <a>1 2</a> :)array { 1 to 2 } + 3 (: error: the left operand returns two items :)</pre> Atomization also applies to function arguments. The following query returns 5, because the array will be atomized to a sequence of 5 integers: <pre lang='xquery'>let $f := function($x as xs:integer*) { count($x) }return $f([1 to 5])</pre> However, the next query returns 1, because the array is already of the general type {{Code|item()}}, and no atomization will take place: <pre lang='xquery'>let $f := function($x as item()*) { count($x) }return $f([1 to 5])</pre> Arrays can be compared with the {{Code|fn:deep-equal}} function. The [[Array Module]] describes the available set of array functions. =Lookup Operator= The lookup operator provides some syntactic sugar to access values of maps or array members. It is introduced by the question mark ({{Code|?}}) and followed by a specifier. The specifier can be: # A wildcard {{Code|*}},# The name of the key,# The integer offset, or# Any other parenthesized expression. The following example demonstrates the four alternatives: <pre lang='xquery'>let $map := map { 'R': 'red', 'G': 'green', 'B': 'blue' }return ( $map?* (: 1. returns all values; same as: map:keys($map) ! $map(.) :), $map?R (: 2. returns the value associated with the key 'R'; same as: $map('R') :), $map?('G','B') (: 3. returns the values associated with the key 'G' and 'B' :)), let $array := [ 'one', 'two', 'three' ]return ( $array?* (: 1. returns all values; same as: (1 to array:size($array)) ! $array(.) :), $array?1 (: 2. returns the first value; same as: $array(1) :), $array?(2 to 3) (: 3. returns the second and third values; same as: (1 to 2) ! $array(.) :))</pre> The lookup operator can also be used without left operand. In this case, the context item will be used as input. This query returns {{Code|Akureyri}}: <pre lang='xquery'>let $maps := ( map { 'name': 'Guðrún', 'city': 'Reykjavík' }, map { 'name': 'Hildur', 'city': 'Akureyri' })return $maps[?name = 'Hildur'] ?city</pre>
Like sequences, maps have no identity. It is meaningful to compare the contents of two maps, but there is no way of asking whether they are "the same map": two maps with the same content are indistinguishable.=Arrow Operator=
Because The arrow operator <code>=></code> provides a map convenient alternative syntax for passing on functions to a value. The expression that precedes the operator will be supplied as first argument of the function that follows the arrow. If <code>$v</code> is a value and <code>f()</code> is a function , then <code>$v => f()</code> is equivalent to <code>f($v)</code>, and <code>$v => f($j)</code> is equivalent to <code>f($v, $j)</code>: <pre lang='xquery'>(: Returns 3 :)count(('A', 'B', 'C')),('A', 'B', 'C') => count(),('A', 'B', 'C') => (function( $sequence) { count( $sequence)})(), (: Returns W-E-L-C-O-M-E :)string-join(tokenize(upper-case('w e l c o m e')), '-'),'w e l c o m e' => upper-case() => tokenize() => string-join('-'), (: Returns xfmdpnf :)codepoints-to-string( for $i in string-to-codepoints('welcome') return $i + 1),(for $i in 'welcome' => string-to-codepoints() return $i + 1) => codepoints-to-string()</pre> The syntax makes nested function calls more readable, as it is easy to see if parentheses are balanced. =String Constructor= The string constructor has been inspired by [https://en.wikipedia.org/wiki/Here_document here document] literals of the Unix shell and script languages. It allows you to generate strings that contain various characters that would otherwise be interpreted as XQuery delimiters. The string constructors syntax uses two backticks and a square bracket for opening and closing a string: <pre lang='xquery'>(: Returns "This is a 'new' & 'flexible' syntax." :)``["This is a 'new' & 'flexible' syntax."]``</pre> XQuery expressions can be embedded via backticks and a curly bracket. The evaluated results will be separated with spaces, and all strings will eventually be concatenated: <pre lang='xquery'>(: Returns »Count 1 2 3, and I will be there.« :)let $c := 1 to 3return ``[»Count `{ $c }`, and I will be there.«]``</pre> =Serialization= Two [[Serialization]] methods have been added to the [https://www.w3.org/TR/xslt-xquery-serialization-31 Serialization spec]: ==Adaptive Serialization== The {{Code|adaptive}} serialization provides an intuitive textual representation for all XDM types, including maps and arrays, functions, attributes, and namespaces. All items will be separated by the value of the {{Code|item-separator}} parameter, which by default is a newline character. It is utilized by the functions {{Function|Profiling|prof:dump}} and <code>[https://www.w3.org/TR/xpath-functions that apply -31/#func-trace fn:trace]</code>. Example: <pre lang='xquery'>declare option output:method 'adaptive';<element id='id0'/>/@id,xs:token("abc"),map { 'key': 'value' },true#0</pre> Result: <pre lang="xml">id="id0"xs:token("abc"),map { "key": "value"}fn:true#0</pre> ==JSON Serialization== The new {{Code|json}} serialization output method can be used to serialize XQuery maps, arrays, atomic values and empty sequences as JSON. The {{Code|json}} output method has been introduced in BaseX before it was added to the official specification. It complies with the standard serialization rules and, at the same time, preserves the existing semantics: * If an XML node of type {{Code|element(json)}} is found, it will be serialized following the serialization rules of the [[JSON Module]].* Any other node or atomic value, map, array, or empty sequence will be serialized according to the [https://www.w3.org/TR/xslt-xquery-serialization-31/#json-output rules in the specification]. The following two queries will both return the JSON snippet <code>{ "key": "value" }</code>: <pre lang='xquery'>declare option output:method 'json';map { "key": "value" }</pre> <pre lang='xquery'>declare option output:method 'json';<json type='object'> <key>value</key></json></pre> =Functions= The following functions have been added in the [https://www.w3.org/TR/xpath-functions-31/ XQuery 3.1 Functions and Operators] Specification: ==Map Functions== <code>map:merge</code>, <code>map:size</code>, <code>map:keys</code>, <code>map:contains</code>, <code>map:get</code>, <code>map:entry</code>, <code>map:put</code>, <code>map:remove</code>, <code>map:for-each</code> Please check out the [[Map Module]] for more details. ==Array Functions== <code>array:size</code>, <code>array:append</code>, <code>array:subarray</code>, <code>array:remove</code>, <code>array:insert-before</code>, <code>array:head</code>, <code>array:tail</code>, <code>array:reverse</code>, <code>array:join</code>, <code>array:flatten</code>, <code>array:for-each</code>, <code>array:filter</code>, <code>array:fold-left</code>, <code>array:fold-right</code>, <code>array:for-each-pair</code> Please check out the [[Array Module]] for more details. ==JSON Functions== With XQuery 3.1, native support for JSON objects was added. Strings and resources can be parsed to XQuery items and, as [[#JSON Serialization|shown above]], serialized back to their original form. ===fn:parse-json=== <pre>fn:parse-json( $json as xs:string? $options as map(*) := ()) as item()?</pre> Parses the supplied string as JSON text and returns its item representation. The result may be a map, an array, a string, a double, a boolean, or an empty sequence. The allowed options can be looked up in the [https://www.w3.org/TR/xpath-functions-31/#func-parse-json specification]. <pre lang='xquery'>parse-json('{ "name": "john" }') (: yields { "name": "json" } :),parse-json('[ 1, 2, 4, 8, 16]') (: yields [ 1, 2, 4, 8, 16 ] :)</pre> ===fn:json-doc=== <pre>fn:json-doc( $href as xs:string? $options as map(*) := ()) as item()?</pre> Retrieves the text from the specified URI, parses the supplied string as JSON text and returns its item representation (see {{Function||fn:parse-json}} for more details). <pre lang='xquery'>json-doc("http://ip.jsontest.com/")('ip') (: returns your IP address :)</pre> ===fn:json-to-xml=== <pre>fn:json-to-xml( $json as xs:string? $options as map(*) := ()) as document-node()?</pre> Converts a JSON string to an XML node representation. The allowed options can be looked up in the [https://www.w3.org/TR/xpath-functions also apply -31/#func-json-to-xm specification]. <pre lang='xquery'>json-to maps-xml('{ "message": "world" }') (: result:<map xmlns="http://www.w3. A org/2005/xpath-functions"> <string key="message">world</string></map> :)</pre> ===fn:xml-to-json=== <pre>fn:xml-to-json( $node as xs:string? $options as map (*) := ()) as xs:string?</pre> Converts an XML node, whose format conforms to the results created by {{Function||fn:json-to-xml}}, to a JSON string representation. The allowed options can be looked up in the [https://www.w3.org/TR/xpath-functions-31/#func-xml-to-json specification]. <pre lang='xquery'>(: returns "JSON" :)xml-to-json(<string xmlns="http://www.w3.org/2005/xpath-functions">JSON</string>)</pre> ==fn:sort== <pre>fn:sort( $input as item()*, $collation as xs:string? := fn:default-collation(), $key as function(item()) as xs:anyAtomicType* := fn:data#1) as item()*</pre> Returns a new sequence with sorted {{Code|$input}} items, using an optional {{Code|$collation}}. If a {{Code|$key}} function is supplied, it will be applied on all items. The items of the resulting values will be sorted using the semantics of the {{Code|lt}} expression. <pre lang='xquery'>sort(reverse(1 to 3)) (: yields 1, 2, 3 :),reverse(sort(1 to 3)) (: returns the sorted order in descending order :),sort((3,-2,1), (), abs#1) (: yields 1, -2, 3 :),sort((1,2,3), (), function($x) { -$x }) (: yields 3, 2, 1 :),sort((1,'a')) (: yields an anonymous error, as strings and integers cannot be compared :)</pre> ==fn:contains-token== <pre>fn:contains-token( $value as xs:string*, $token as xs:string, $collation as xs:string? := fn:default-collation()) as xs:boolean</pre> The supplied strings will be tokenized at whitespace boundaries. The functionreturns {{Code|true}} if one of the strings equals the supplied token, so possibly under the rules of a supplied collation: <pre lang='xquery'>contains-token(('a', 'b c', 'd'), 'c') (: yields true :)<xml class='one two'/>/contains-token(@class, 'one') (: yields true :)</pre> ==fn:parse-ietf-date== <pre>fn:parse-ietf-date( $value as xs:string?) as xs:dateTime?</pre> Parses a string in the IETF format (which is widely used on the Internet) and returns a {{Code|xs:dateTime}} item: <pre lang='xquery'>fn:parse-ietf-date('28-Feb-1984 07:07:07')" (: yields 1984-02-28T07:07:07Z :),fn:parse-ietf-date('Wed, 01 Jun 2001 23:45:54 +02:00')" (: yields 2001-06-01T23:45:54+02:00 :)</pre> ==fn:apply== <pre>fn:apply( $function as function(*), $arguments as array(*)) as item()*</pre> The supplied {{Code|$function-name}} returns is invoked with the empty sequence; specified {{Code|$arguments}}. The arity of the function must be the same as the size of the array. Example: <pre lang='xquery'>fn:apply(concat#5, array { 1 to 5 }) (: 12345 :)fn:apply(function($a) { sum($a) }, [ 1 to 5 ]) (: 15 :)fn:apply(count#1, [ 1,2 ]) (: error. the array has two members :)</pre> ==fn:random-number-aritygenerator== <pre>fn:random-number-generator( $seed as xs:anyAtomicType? := ()) as map(xs:string, item())</pre> Creates a random number generator, using an optional seed. The returned map contains three entries: * {{Code|number}} is a random double between 0 and 1* {{Code|next}} always is a function that returns another random number generator* {{Code|1permute}}is a function that returns a random permutation of its argument The returned random generator is ''deterministic'': If the function is called twice with the same arguments and in the same execution scope, it will always return the same result. Example: <pre lang='xquery'>let $rng := fn:random-number-generator()let $number := $rng('number') (: returns a random number :)let $next-rng := $rng('next')() (: returns a new generator :)let $next-number := $next-rng('number') (: returns another random number :)let $permutation := $rng('permute')(1 to 5) (: returns a random permutation of (1,2,3,4,5) :)return ($number, $next-number, $permutation)</pre> ==fn:format-number== The function has been extended to support scientific notation: <pre lang='xquery'>format-number(1984.42, '00.0e0') (: yields 19.8e2 :)</pre>
Maps may be compared using the {{Code|==fn:deep-equal}} function. The [[Map Module]] describes the available set of map functions.tokenize==
==Arrays==If no separator is specified as second argument, a string will be tokenized at whitespace boundaries:
An <pre lang='xquery'array'' is >fn:tokenize(" a function that associates b c d") (: yields "a set of positions, represented as positive integer keys", with values. The first position in an array is associated with the integer {{Code|1}}. The values of an array are called its members. In the type hierarchy"b", array has a distinct type"c", which is derived from function."d" :)</pre>
==fn:trace==
The function corresponding to the array has the signature {{Code|function($index as xssecond argument can now be omitted:integer) as item()*}}. The expression {{Code|$array($index)}} returns the associated member. The fact that an array is a function item allows it to be passed as an argument to higher-order functions that expect a function item as one of their arguments.
Like all other values, arrays are immutable. For example<pre lang='xquery'>fn:trace(<xml/>, "Node: ")/node() (: yields the debugging output "Node: <codexml/>[[Array Module#array" :reverse|array),fn:reverse]]trace(<xml/code> function creates a new array containing a re-ordering of )/node() (: returns the members of an existing array, but the existing array is not changed by the operation.debugging output "<xml/>" :)</pre>
Like sequences, arrays have no identity. It is meaningful to compare the contents of two arrays, but there is no way of asking whether they are "the same array"==fn: two arrays with the same content are indistinguishable.string-join==
Arrays may The type of the first argument is now <code>xs:anyAtomicType*</code>, and all items will be compared using the {{Code|fnimplicitly cast to strings:deep-equal}} function. The [[Array Module]] describes the available set of array functions.
<pre lang==Functions=='xquery'>fn:string-join(1 to 3) (: yields the string "123" :)</pre>
The following functions of the [http==fn://www.w3.org/TR/xpathdefault-functions-31/ XQuery 3.1 Functions and Operators] Working Draft have already been implemented:language==
* [[Map ModuleReturns the default language used for formatting numbers and dates. BaseX always returns {{Code|Map functions]]: <code>map:merge</code>, <code>map:size</code>, <code>map:keys</code>, <code>map:contains</code>, <code>map:get</code>, <code>map:entry</code>, <code>map:put</code>, <code>map:remove</code>, <code>map:for-each-entry</code><code>fn:contains-token</code>, * Array functions: <code>array:size</code>, <code>array:append</code>, <code>array:subarray</code>, <code>array:remove</code>, <code>array:insert-before</code>, <code>array:head</code>, <code>array:tail</code>, <code>array:reverse</code>, <code>array:join</code>, <code>array:for-each-member</code>, <code>array:filter</code>, <code>array:for-each-pair</code>en}}.
New signatures have been added for the following functions:==Appendix==
The three functions <code>fn:tokenizetransform</code>, <code>fn:load-xquery-module</code> and <code>fn:collation-key</code> may be added in a future version of BaseX as their implementation might require the use of additional external libraries.
==Binary Data==
Items of type <code>xs:hexBinary</code> and <code>xs:base64Binary</code> can now be compared against each other. The following queries all yieldl yield {{Code|true}}:
<pre classlang="brush:'xquery"'>
xs:hexBinary('') < xs:hexBinary('bb'),
xs:hexBinary('aa') < xs:hexBinary('bb'),
</pre>
==Pending Features=Collations=
XQuery 3.1 is still subject to changeprovides a default collation, but the following features and functions will be added soonwhich allows for a case-insensitive comparison of ASCII characters (<code>A-Z</code> = <code>a-z</code>). This query returns <code>true</code>:
* Arrow operator (<code>pre lang='xquery'><declare default collation 'http://code>): applies a function to an item, using the item as the first argument to the functionwww.w3. The expression <code>$i=>$f()<org/code> is equivalent to <code>$f($i)<2005/code>, and <code>$i=>$f($j)<xpath-functions/code> is equivalent to <code>$f($i, $j)<collation/code>.html-ascii-case-insensitive';'HTML' = 'html'* Map lookup operator (<code>?</codepre>) If the [http: returns the value of a map for a specific key//site.icu-project. The expression <code>$map('name')<org/code> download ICU Library] is equivalent downloaded and added to <code>$map?name<the classpath, the full [https://code>www.w3.* Support for JSON: <code>fn:jsonorg/TR/xpath-functions-doc<31/code>, <code>fn#uca-collations Unicode Collation Algorithm] features become available in BaseX:parse-json </codepre lang='xquery'>* New functions(: <code>arrayreturns 0 (both strings are compared as equal) :fold)compare('a-left</code>b', 'ab', <code>array'http:fold-right</code>, <code>fn:/www.w3.org/2013/collation-key/UCA?alternate=shifted')</codepre> =Enclosed Expressions= ''Enclosed expression'' is the syntactical term for the expressions that are specified inside a function body, <code>fn:load-module<try/code>catch clauses, node constructors and some other expressions. In the following example expressions, its the empty sequence: <codepre lang='xquery'>fndeclare function local:parse-ietf-datex() { () };try { () } catch * { () },element x { () },text { () }</codepre> With XQuery 3.1, <code>fnthe expression can be omitted. The following query is equivalent to the upper one:transform </codepre lang='xquery'>, <code>mapdeclare function local:for-each-entry</code>x() { };try { } catch * Support for scientific notation: <code>format-number{ },element x { }text { }</codepre>
=Changelog=
;Version 8.6
* Updated: Collation argument was inserted between first and second argument.
;Version 8.4
* Added: [[#String Constructors|String Constructors]], {{Code|fn:default-language}}, [[#Enclosed Expressions|Enclosed Expressions]]
* Updated: [[#Adaptive Serialization|Adaptive Serialization]], {{Code|fn:string-join}}
;Version 8.2
* Added: {{Code|fn:json-to-xml}}, {{Code|fn:xml-to-json}}.
;Version 8.1
* Updated: arrays are now based on a [https://en.wikipedia.org/wiki/Finger_tree Finger Tree] implementation.
Introduced with Version 8.0.
[[Category:XQuery]]