Reference · Lists

sum

signature
sum(list | null) -> any

What it does

The items added together, starting from 0. Ints give an int, a float anywhere gives a float, and decimals stay exact and give a decimal. An empty list or null gives 0.

Examples

print(sum([1, 2, 3]))print(sum([1, 2.5]))print(sum([dec("0.10"), dec("0.20")]))let orders = [{ total: 10 }, { total: 7 }]print(sum(map(orders, (o) => o.total)))
output
63.50.3017

Edge cases

print(sum([]), sum(null), type_of(sum([])))print(sum([0.1, 0.2]), sum([dec("0.1"), dec("0.2")]), sum([dec("1.5"), 2]))print(["12.50", "5.00"] | map(dec) | sum)
output
0 0 int0.30000000000000004 0.3 3.517.50

Errors

An argument that is not a list or null is a runtime error, not an error value. A string among the items is a runtime error naming it and its place, and saying what to write. An item that + cannot add to the total so far (null, a boolean, a list, a map) is a runtime error, and so is a decimal met with a float, or an int overflow.

this one fails
print(sum([1, 2, "3"]))
output
line 1: `sum` adds numbers; got the str "3" at item 2: use `float(...)` or `dec(...)` first
this one fails
print(sum([1, null, 2]))
output
line 1: cannot add int and null
this one fails
print(sum([dec("0.1"), 0.2]))
output
line 1: cannot add dec and float: a dec is exact and a float is not, so convert one with dec(x) or float(x)
this one fails
print(sum([9223372036854775807, 1]))
output
line 1: integer overflow

Chaining

In a pipeline sum takes the list and needs no arguments: xs | map(f) | sum.

print([1, 2, 3, 4] | filter((x) => x % 2 == 0) | sum)print("1,2,3" | split(",") | map(int) | sum)print(range(1, 101) | sum)
output
665050

See also

reduce, min, max, count, stats.mean, math.fsum

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On sum(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo