Returns a value obtained by adding together the values in $arg
.
fn:sum
( $arg
as xs:anyAtomicType*
xs:anyAtomicType
fn:sum
( $arg
as xs:anyAtomicType*
,$zero
as xs:anyAtomicType?
xs:anyAtomicType?
Any values of type xs:untypedAtomic
in $arg
are cast to
xs:double
. The items in the resulting sequence may be reordered in an
arbitrary order. The resulting sequence is referred to below as the converted
sequence.
If the converted sequence is empty, then the single-argument form of the function
returns the xs:integer
value 0
; the two-argument form returns
the value of the argument $zero
.
If the converted sequence contains the value NaN
, NaN
is
returned.
All items in $arg
must be numeric or derived from a single base type. In
addition, the type must support addition. Duration values must either all be
xs:yearMonthDuration
values or must all be
xs:dayTimeDuration
values. For numeric values, the numeric promotion
rules defined in are used to promote all values to a single
common type. The sum of a sequence of integers will therefore be an integer, while the
sum of a numeric sequence that includes at least one xs:double
will be an
xs:double
.
The result of the function, using the second signature, is the result of the expression:
if (fn:count($c) eq 0) then $zero else if (fn:count($c) eq 1) then $c[1] else $c[1] + fn:sum(subsequence($c, 2))
where $c
is the converted sequence.
The result of the function, using the first signature, is the result of the expression:
fn:sum($arg, 0)
.
let $d1 := xs:yearMonthDuration("P20Y")
let $d2 := xs:yearMonthDuration("P10M")
let $seq1 := ($d1, $d2)
let $seq3 := (3, 4, 5)
The expression fn:sum(($d1, $d2))
returns xs:yearMonthDuration("P20Y10M")
.
The expression fn:sum($seq1[. lt xs:yearMonthDuration('P3M')],
xs:yearMonthDuration('P0M'))
returns xs:yearMonthDuration("P0M")
.
The expression fn:sum($seq3)
returns 12
.
The expression fn:sum(())
returns 0
.
The expression fn:sum((),())
returns ()
.
The expression fn:sum((1 to 100)[. lt 0], 0)
returns 0
.
fn:sum(($d1, 9E1))
raises a type error .
The expression fn:sum(($d1, $d2), "ein Augenblick")
returns xs:yearMonthDuration("P20Y10M")
.
The expression fn:sum([1, 2, 3])
returns 6
.
The expression fn:sum([[1, 2], [3, 4]])
returns 10
.
A type error is raised if the input sequence contains items of incompatible types, as described above.
The second argument allows an appropriate value to be defined to represent the sum of an empty sequence. For example, when summing a sequence of durations it would be appropriate to return a zero-length duration of the appropriate type. This argument is necessary because a system that does dynamic typing cannot distinguish "an empty sequence of integers", for example, from "an empty sequence of durations".
If the converted sequence contains exactly one value then that value is returned.