Rima Manual: Sums

[ Contents | Previous: Arrays | Next: A Blending Problem ]

Summing the elements of a table is achieved with rima.sum{tables}(expression), which takes a list of tables to sum over as its first argument, and an expression to sum as its second:


x, X = rima.R"x, X"
e = rima.sum{x=X}(x)
print(e)                                            --> sum{x in X}(x)
print(rima.E(e, {X={4, 5, 6}}))                     --> 15

The {x=X} syntax is especially useful if you want to sum over the same table more than once:


x1, x2, X = rima.R"x1, x2, X"
e = rima.sum{x1=X, x2=X}(x1 * x2)
print(rima.E(e, {X={2, 3, 4}}))                     --> 81

Often, you'll want your sum expression to operate on data from more than one array:


i, Y, Z = rima.R"i, Y, Z"
e = rima.sum{i=Y}(Y[i] * Z[i])
print(rima.E(e, {Y={3,5,7}, Z={7,5,3}}))            --> 67

Notice than in this example, we used the "bound variable" (i) as and index to a subscript, whereas in the previous example, we used the bound variable (x) directly in an expression.

Rima knows the difference between using a bound variable in an index expression, and as a value, and tries to do the right thing, but it can get confused, so it's best to approach this with caution.

As a better, but less familiar alternative, Rima offers the ipairs iterator (which is much like Lua's ipairs). ipairs returns two values per iteration, the array index and the array value:


i, x, X = rima.R"i, x, X"
e = rima.sum{["i, x"]=rima.ipairs(X)}(i * x)
print(rima.E(e, {X={3,5,7}}))                      --> 34

The syntax for ipairs - ["i, x"]=rima.ipairs(X) is a little convoluted, but that's the what we have to do to work in with Lua's syntax.

Alternatively, you can use rima.ord to get the index of an array element:


x, X = rima.R"x, X"
e = rima.sum{x=X}(rima.ord(x) * x)
print(rima.E(e, {X={3,5,7}}))                      --> 34

When summing over more than one array, it's often useful to use a separate array that defines the indexes to sum over. rima.sum works quite hard to do what you mean when you index arrays, hard enough that arrays can be used like sets in other modelling languages:


s, S, count = rima.R"s, S, count"
e = rima.sum{s=S}(count[s])
SS = { "north", "south", "east", "west" }
COUNT = { 1, 2, 4, 8 }
print(rima.E(e, {S=SS, count=COUNT}))               --> 15

[ Contents | Previous: Arrays | Next: A Blending Problem ]