Sequence Functions

head(), tail(), subsequence(), insert-before(), remove() and reverse() rearrange; index-of() finds positions; distinct-values() deduplicates; sort() (new in 3.1) takes an optional key function. The guards zero-or-one(), one-or-more() and exactly-one() turn a missing or duplicated record into an error:

Deduplicating, sorting and guarding the catalog's sequences
xp 'index-of(//subject, "Fiction")' 'distinct-values((1, 1.0, "1", xs:double(1)))' \
   'sort(//book, (), function($b) { -xs:decimal($b//price) })[1]/@id ! string()' \
   'exactly-one(//book[@id = "b9"])'
Output
index-of(//subject, "Fiction")         => 1
distinct-values((1, 1.0, "1", xs:double(1))) => 1 "1"
sort(//book, (), function($b) { -xs:decimal($b//price) })[1]/@id ! string() => "b2"
exactly-one(//book[@id = "b9"])        => error FORG0005

index-of() compares with eq, so "Science Fiction" does not match. distinct-values() merges the numeric 1s, in no promised order. The sort key negates a decimal to sort by price, descending, as a number.


Sequence Functions

Sequence functions test, rearrange, and aggregate sequences of items. See Sequence, Flow Control, and Typing for the sequence constructors and operators these functions work with.
empty((1,2))false
exists((1,2))true
head((1,2,3))1
tail((1,2,3))(2,3)
insert-before((1,2,3),2,(4,5))(1,4,5,2,3)
remove((1,2,3),2)(1,3)
reverse((1,2,3))(3,2,1)
subsequence((1,2,3,4,5),2,2)(2,3)
unordered((1,2,3,4,5))(1,2,3,4,5)
distinct-values((1,2,3,2,1))(1,2,3)
index-of((10,20,30,30,40,50),30)(3,4)
deep-equal((1,2,3),(1,(2),3))true
zero-or-one((10))10
zero-or-one(())()
one-or-more((1,2,3))(1,2,3)
exactly-one((10))10
count((1,2,3))3
avg((3,4,7))4.6666666667
max((1,2,3))3
min((1,2,3))1
sum((1,2,3))6
ch03-sequence-functions.xpath.txt
merged-01-01-ch03-sequence-functions.xpath.txt
distinct-values((1,2,3,2,1))
Output
(1, 2, 3)