Sum (Arraylist function)

From m204wiki
Jump to navigation Jump to search

Compute the sum of the items (Arraylist class)

[Introduced in Sirius Mods 7.8]


Syntax

%sum = al:Sum[( [itemFunction])]

Syntax terms

%sum A Float variable to contain the numeric result.
al An Arraylist object.
itemFunction A function that operates on the type of the items in the Arraylist. It may be a local method or method variable or a class member (Variable, Property), and it must return an intrinsic (probably Float) value.

The default itemFunction value is the special identity function, This, which simply returns the item value.

Usage notes

  • The optional itemFunction parameter lets you further manipulate the Arraylist item values before calculating the sum. The itemFunction default (identity function This) fails against non-intrinsic values, however. If your collection items are not intrinsic values, you must specify an itemFunction function that can map the item values to intrinsic values.

    For example, for an Arraylist that is a list of coordinates, you could return the sum of their distance from the origin by first applying a local function as the Sum method's itemFunction parameter:

    b class point public constructor new(%x is float, %y is float) variable x is float variable y is float end public constructor new(%x is float, %y is float) %this:x = %x %this:y = %y end constructor end class local function (point):distance is float return (%this:x * %this:x + %this:y * %this:y):squareRoot end function %al is arrayList of object point %al = new %al:add(new(1,1)) %al:add(new(3,4)) %al:add(new(-5,12)) print %al:sum(distance) end

    The result is 19.4142135623731.

Examples

b %al is arrayList of float %al = new %al = list(5, 3, 8) print %al:sum end

The result is:

16

See also