Reference · Lists
sum
sum(list | null) -> anyWhat 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)))63.50.3017Edge cases
sum([])andsum(null)are0, an int.- Floats add as floats do:
0.1 + 0.2is0.30000000000000004. Decimals do not drift, and an int with a decimal gives a decimal. - A total of ints that passes what an int holds is a runtime error, not a float.
- Text is not a number, even when it holds one: amounts read from a form, a CSV or the
session are text, and
sumrefuses them at the first, rather than join them. Make them numbers first,map(dec)for money ormap(float); use join for text.
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)0 0 int0.30000000000000004 0.3 3.517.50Errors
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.
print(sum([1, 2, "3"]))line 1: `sum` adds numbers; got the str "3" at item 2: use `float(...)` or `dec(...)` firstprint(sum([1, null, 2]))line 1: cannot add int and nullprint(sum([dec("0.1"), 0.2]))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)print(sum([9223372036854775807, 1]))line 1: integer overflowChaining
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)665050See also
reduce, min, max, count, stats.mean, math.fsum
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