How to calculate many sums in a single foreach relating the same data?

Certified Senior Developer

Hi,

Here is a little code example below of a 3 sum calculation with 3 foreach relating on the same data.

Is there any way to optimize this code to keep a single foreach left and then storing the sum outputs in a an array or a list of 3 items (or other)?

A kind of:

local!sumArray: a!foreach(

   sum(), sum(), sum()

)

local!sumA: sum(
  a!forEach(
    items: ri!data,
    expression: if (fv!item.weight > 0,
	  1,
      0
    )
  )
),
local!sumB: sum(
  a!forEach(
    items: ri!data,
    expression: if (fv!item.weight > fv!item.weight2,
      1,
      0
    )
  )
),
local!sumC: sum(
  a!forEach(
    items: ri!data,
    expression: fv!item.weight,
  )
)

  Discussion posts and replies are publicly visible

Parents
  • Why not just have the forEach loop construct a dictionary?  You can at least condense it down to only a single a!forEach loop over ri!data, though I don't immediately think of any way to do all the sum() operations in the same spot (but they're simpler at least)

    i.e.

    local!dictionary: a!forEach(
      items: ri!data,
      expression: {
        partA: if(fv!item.weight > 0, 1, 0),
        partB: if(fv!item.weight > fv!item.weight2, 1, 0),
        weight1: fv!item.weight,
        weight2: fv!item.weight2
      }
    ),
    
    local!sumA: sum(local!dictionary.partA),
    local!sumB: sum(local!dictionary.partB),
    local!sumC: sum(local!dictionary.weight1),
    
    ...

Reply
  • Why not just have the forEach loop construct a dictionary?  You can at least condense it down to only a single a!forEach loop over ri!data, though I don't immediately think of any way to do all the sum() operations in the same spot (but they're simpler at least)

    i.e.

    local!dictionary: a!forEach(
      items: ri!data,
      expression: {
        partA: if(fv!item.weight > 0, 1, 0),
        partB: if(fv!item.weight > fv!item.weight2, 1, 0),
        weight1: fv!item.weight,
        weight2: fv!item.weight2
      }
    ),
    
    local!sumA: sum(local!dictionary.partA),
    local!sumB: sum(local!dictionary.partB),
    local!sumC: sum(local!dictionary.weight1),
    
    ...

Children