Q: I just have a simple question, because I cannot find some example about it. It is possible to iterate over a collection (arrays, list, etc) just to calculate some values in a function, when executing the simulation?

I want to calculate “mean” and “deviation” values, taking them from indexing 2 arrays I have in the declaration, to later send them as parameters for a normal distribution function (simulating a delay()). I need to use direct indexes like: if I have an array a=[100,250,300] in the declaration, then in a function I can get a[i], being i: 1..3. So, I can do calculations like a[i]+b[i]; a[i]/b[i]; etc.

I tried defining “colset”, “list” and also with “val”. Any of them is ok, because the values are constant and defined on the declaration section, just to index them I received a “i” value during simulation, so I need to do a[i], that’s it.

Can you help me please? Do you have some easy example?. I already checked CPN Tools examples and SML manuals, but I didn’t see this case.

Thank you in advance for any help you can give me.

A: You could use the list functions for this. In your case, if a is your list and i is your index (with base 1), then `List.nth(a, i-1)`

provides you with a[i]. Note that you use arrays with base 1, whereas Standard ML uses lists with base 0, that’s why we need `i-1`

.

You may also want to take a look at the Standard ML list structure. It contains generic list functions, and in particular the two fold functions. http://sml-family.org/Basis/list.html#SIG:LIST.foldl:VAL

The fold functions implement the same paradigm you may know as Googles MapReduce (actually MapReduce was inspired by the fold functions).

That allows you to implement a list sum and average functions as:

fun intSum (a, b) = a + b

fun listSum lst = List.foldl intSum 0 lst

fun listAvg [] = 0 | listAvg lst = (listSum lst) div (List.length lst)

Note the average has several issues: it uses integer division, so `listAvg [1, 2] = 1`

and it is prone to overflows, so `listAvg [1000000000, 1000000000]`

will fail.

The `intSum`

function is a misnomer; it will also work with lists of real. `listSum`

and `listAvg`

will only work with ints (because of `0`

and `div`

; use `0.0`

and `/`

instead to make it use with reals).