adding numbers present in array without using sum function

Certified Associate Developer

can some one tell me on how to create an expression rule to add an array of numbers without suing sum function

  Discussion posts and replies are publicly visible

Parents
  • Agree, sum() function should be your go-to for "summing" an array.  

    But if you are looking to unnecessarily complicate your code, how about a recursive function to add an array of numbers.

    Note with recursive rules, you must save them prior to testing.

    /* 
    rule!chris_add_recur(
      array: List of Integer
      index: Integer
      total: Integer
    )
    */
    
    a!localVariables(
      local!index: if(rule!APN_isEmpty(ri!index),1,ri!index),
      local!total: if(rule!APN_isEmpty(ri!total),0,ri!total),
      
      if(
        local!index>count(ri!array),
        ri!total,
        rule!chris_add_recur(
          array: ri!array,
          index: local!index+1,
          total: index(ri!array,local!index)+local!total
        )
      )
    )

    Call this rule with only the array input as:

    rule!chris_add_recur(
      array: {1,2,3,4}
    )

Reply
  • Agree, sum() function should be your go-to for "summing" an array.  

    But if you are looking to unnecessarily complicate your code, how about a recursive function to add an array of numbers.

    Note with recursive rules, you must save them prior to testing.

    /* 
    rule!chris_add_recur(
      array: List of Integer
      index: Integer
      total: Integer
    )
    */
    
    a!localVariables(
      local!index: if(rule!APN_isEmpty(ri!index),1,ri!index),
      local!total: if(rule!APN_isEmpty(ri!total),0,ri!total),
      
      if(
        local!index>count(ri!array),
        ri!total,
        rule!chris_add_recur(
          array: ri!array,
          index: local!index+1,
          total: index(ri!array,local!index)+local!total
        )
      )
    )

    Call this rule with only the array input as:

    rule!chris_add_recur(
      array: {1,2,3,4}
    )

Children