An array is one item, so arrays nest, and each member may be a whole sequence. array:size(), array:get() (or $a?n), array:put(), array:append(), array:subarray(), array:remove(), array:join() and array:flatten() reshape them; array:for-each(), array:filter(), array:fold-left(), array:fold-right() and array:sort() take functions.
xp 'let $a := [1, "a", ["c", map { "x": 0 }]] return $a?3?2?x' \
'[1, (2, 3), ()]' 'array { 1, (2, 3), () }' \
'array:fold-right(["a", "b", "c"], "d", function($m, $acc) { $acc || $m })'Output
let $a := [1, "a", ["c", map { "x": 0 }]] return $a?3?2?x => 0
[1, (2, 3), ()] => [1,(2,3),()]
array { 1, (2, 3), () } => [1,2,3]
array:fold-right(["a", "b", "c"], "d", function($m, $acc) { $acc || $m }) => "dcba"Square brackets make one member per expression, curly braces one per item. array:fold-right() passes the member before the accumulator, the reverse of array:fold-left(). Reading past the end raises FOAY0001.
Array Functions
Arrays are ordered, index-addressable sequences of items, written with square brackets (e.g. [1,2,3]); they were introduced, together with maps, in XPath 3.1 (see XPath). The array: functions below operate on arrays; XPath 4.0, currently under development by the W3C's QT4CG and not yet a Recommendation, is expected to extend array and JSON support further. Each function is evaluated against:| let $a := [1,2,3,"a","b",["c",{"x":0}]] return … |
| array:size($a) | 6 |
| array:get($a,4) | a |
| array:put($a,2,"z") | [1, "z", 3, "a", "b", ["c", {"x":0}]] |
| array:append($a,"z") | [1, 2, 3, "a", "b", ["c", {"x":0}], "z"] |
| array:subarray($a,2,2) | [2, 3] |
| array:remove($a,6) | [1, 2, 3, "a", "b"] |
| array:insert-before($a,2,"z") | [1, "z", 2, 3, "a", "b", ["c", {"x":0}]] |
| array:head($a) | 1 |
| array:tail($a) | [2, 3, "a", "b", ["c", {"x":0}]] |
| array:reverse($a) | [["c", {"x":0}], "b", "a", 3, 2, 1] |
| array:for-each([2,4,6], function($e){$e*10}) | [20, 40, 60] |
| array:filter([2,4,6], function($e){$e<5}) | [2, 4] |
| array:fold-left(["a","b","c"], "d", function($acc,$e){$e||$acc}) | cbad |
| array:fold-right(["a","b","c"], "d", function($acc,$e){$e||$acc}) | dcba |
| array:for-each-pair([1,2,3], ["a","b","c"], function($a,$b){$a||$b}) | ["1a", "2b", "3c"] |
| array:sort([1,200,30]) | [1, 30, 200] |
| array:flatten(([1, 2, 5], [[10, 11], 12], [], 13)) | 1 2 5 10 11 12 13 |
merged-01-01-ch03-array-functions.xpath.txt
let $a := [1,2,3,"a","b",["c",{"x":0}]]
return array:sort([1,200,30])
Output
[1, 30, 200]