Function reduce() and list of maps

Certified Senior Developer

Hi,

i have the following code

a!localVariables(
local!sensor: {
a!map(data: { 125, 92, 22, 63, 73, 28, 19 }),
a!map(data: { 35, 65, 92, 22, 63, 73, 28 }),
a!map(data: { 2, 35, 65, 22, 63, 73, 18, 29 }),
a!map(data: { 9, 35, 65, 63, 35, 28, 19 })
},
reduce(fn!sum, 0, local!sensor.data)
)


Using excel the sum of all numbers is 1361.

Using reduce() in Appian, the sum is 1332 that is 1361-29.
The value 29 is the eighth element of the third map.
Every map has 7 elements.

Why the reduce() function exlude the element 29?

  Discussion posts and replies are publicly visible

Parents
  • The reduce() function loops on the list of lists that you've provided and the fourth list is one item longer than the others (i.e. the value 29). The function can only work correctly on lists that are the same length. To make it work you'll need to add an additional value 0 to all of the lists that are longer thus:

    a!localVariables(
      local!sensor: {
        a!map(data: { 125, 92, 22, 63, 73, 28, 19, 0 }),
        a!map(data: { 35, 65, 92, 22, 63, 73, 28, 0 }),
        a!map(data: { 2, 35, 65, 22, 63, 73, 18, 29 }),
        a!map(data: { 9, 35, 65, 63, 35, 28, 19, 0 })
      },
      reduce(fn!sum, 0, local!sensor.data)
    )

    Alternatively, you can flatten the list and then simply use fn!sum() thus:

    a!localVariables(
      local!sensor: {
        a!map(data: { 125, 92, 22, 63, 73, 28, 19 }),
        a!map(data: { 35, 65, 92, 22, 63, 73, 28 }),
        a!map(data: { 2, 35, 65, 22, 63, 73, 18, 29 }),
        a!map(data: { 9, 35, 65, 63, 35, 28, 19 })
      },
      fn!sum(
        a!flatten(local!sensor.data)
      )
    )

  • Yeah I can't really think of a scenario where you would use reduce with the sum() function. Stewart is correct, but for sum you don't even need to flatten it - just sum(local!sensor.data) will work too!

Reply Children