s = 0 for k in range(0, N): s += a[k]
Ok, I have more cores/CPUs, could I do it in parallel? Sure
v1 = Sum(0, N/2) v2 = Sum(N/2, N) s = v1 + v2
I even could do it on asymmetric cores (like most phone CPUs today)
v1 = Sum(0, K) v2 = Sum(K, N) s = v1 + v2
I could do a bit more complicated things, like calculating means. For that, I have to make a monoid
def mean(from, to, a): m = 0 for k in range(from, to): m += a[k] N = to - from return (m/N, N)
Here I'm returning tuple, and for that to be a monoid I have to state composition law:
def compose(M1, M2): A1, N1 = M1 A2, N2 = M2 N = N1+N2 return ((A1N1 + A2N2)/N, N)
If my identity is (0,0) tuple, it is quite easy to verify that indeed I have a monoid. Nice, simple, composable ranges.
For closed [1...N] ranges this is NOT nice, NOT simple, just plain fugly exercise. Sorry, looks like code samples are screwed up a bit, don't know how to fix it