Tinderbox v9 Icon

List/Set.sum_if(loopVar, condition[, expressionStr])


Operator Type: 

Operator Scope of Action: 

Operator Purpose: 

Operator First Added: 

Operator Last Altered: 

Operator Has Optional Arguments: 

Operator Has Conditional Arguments: 

Operator Uses Loop Variable Argument: 


List/Set.sum_if(loopVar, condition[, expressionStr])

The dot-operator .sum_if() sums the values of members of a list that satisfy a condition. Each item in the list is bound in turn to loopVar, and if condition is met, the items value is added to the retuned sum. Optionally, the expressionStr is evaluated, allowing a transform to be carried out on a matched list member's value before it is added to the overall returned sum.

loopVar is essentially the same as the loop variable used by the List.each() operator. In the examples below, for clarity the loopVar value "anItem" is used, but as with any loop variable a shorter less expressive values such a "x" can be used (e.g. by more expert users).

The condition argument is a conditional expression for which each tested item must return true or false.

The operator applies the action code expressionStr to only those list items for which condition is true. For only list items meeting condition, the result of expressionStr on loopVar is returned as List-type data.

For example, if $MyList is "1;2;3;4;5", then

$MyListA = $MyList.sum_if(aValue, aValue>3) 

returns the sum of all the members of $MyList that are greater than 3.

An optional third argument expressionStr allows a matched values to be transformed before they are added to the sum. So:

$MyListA = $MyList.sum_if(aValue, aValue>3, aValue*aValue) 

returns the sum of the squares of each member that is greater than 3.

List/Set.sum_if() vs. sum_if()

Although the two appear similar. This operator works directly on the source list values, whereas sum_if() creates a list of $Path values and returns on an attribute value from each of those paths (where the item at the $Path meets the condition).