sum
ErrorsCollection

sum

Synthesised documentation from type/Range type/Any type/List

From type/Range

See Original text in context

multi method sum(Range:D:)

Returns the sum of all elements in the Range. Throws X::Str::Numeric if an element can not be coerced into Numeric.

(1..10).sum                                       # 55

From type/Any

See Original text in context

method sum() is nodal

If the content is iterable, it returns the sum of the values after pulling them one by one, or 0 if the list is empty.

(3,2,1).sum# OUTPUT: «6␤» 
say 3.sum;   # OUTPUT: «3␤» 

It will fail if any of the elements cannot be converted to a number.

From type/List

See Original text in context

sub    sum($list  )
method sum(List:D:)

Returns the sum of all elements in the list or 0 if the list is empty. Throws an exception if an element can not be coerced into Numeric.

say (13pi).sum;       # OUTPUT: «7.14159265358979␤» 
say (1"0xff").sum;      # OUTPUT: «256␤» 
say sum(0b11115);       # OUTPUT: «20␤»

If the list includes a Junction, the result will accordingly be a Junction:

say ( 1|2, 3).sum;            # OUTPUT: «any(4, 5)␤» 

When called on native integer arrays, it is also possible to specify a :wrap named parameter. This will add the values as native integers, wrapping around if they exceed the size of a native integer. If you are sure you will not exceed that value, or if you don't mind, using :wrap will make the calculation about 20x as fast.

my int @values = ^1_000_000;
say @a.sum(:wrap);        # OUTPUT: «499999500000␤»