sum
sum(numbers: Bag<Integer>) : Integer
sum(numbers: Bag<Float>) : Float
The sum of a collection of integer numbers or a collection of floating-point numbers.
- For example, on integers,
sum([1, 2, 3])equals6. - Likewise, on floats,
sum([1.1, 2.1, 3.1])equals6.300000000000001.- Keep in mind that floating-point arithmetic is generally not precise!
- You can define a collection in various ways, not just as a list of literal numbers.
- See Collections for more detail on working with collections.
- Importantly, a collection's elements must all be of the same type. As such,
sum([1.1, 2, 3.1])has a type-error since the list is not well-formed. The fix is to replace integer2with2.0or2.to have it be treated as a float. - You can use
intandfloatto convert to integers and to floats, respectively.
- Note that this method accepts both
ListsandBags─since Lists subtype Bags