I'm trying to get the sum from a list.

The list newTotal:

{"30.00", "30.00"}

repeat with each from 1 to count of items of newTotal
    set myFinalTotal to myFinalTotal + each
end repeat

But the result is unexpected = 3

How should I do the math?


Modifying your original attempt:

set myList to {"30.00", "30.00"}
set myFinalTotal to 0

repeat with x in myList
    set myFinalTotal to myFinalTotal + x
end repeat


And for the joy of learning:

  • Recursive:

    to sumItems from L as list
        if L = {} then return 0
        (L's first item) + (sumItems from the rest of L)
    end sumItems
  • Iterative:

    to sumItems from L as list
        tell (a reference to last item of {0})
            repeat while L ≠ {}
                set the contents to it + (L's first item)
                set L to the rest of L
            end repeat
            return the contents
        end tell
     end sumItems

Solved : I'm counting the list first then do my repeat statement

set sum to 0
set n to count newTotal

repeat with i from 1 to n
    set sum to sum + (item i of newTotal)
end repeat

return sum

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .