For-loop syntax inside of reduce_sum

Hi!

The answer to this question is probably going to come down to “personal preference” but I figured it could be worth asking anyway in case anyone else has the same question. I was recently recommended to check out brms Stan code for guidance on how to specify complicated reduce_sum functions. I noticed a possible quirk whenever there are for-loops inside the partial sum function, and I’m curious if this is best practice or whether it doesn’t really matter for performance.

All the brms Stan code I looked at does something like this for for-loops.

int N = end - start + 1;
for (n in 1:N) {
   int nn = n + start - 1; 
   // ...
}

But I know that this would also get the job done.

for (n in start:end) {
   // ...
}

What’s the difference that I’m not seeing, if any?

This is appears to just be a trick brms uses to simplify the code generation between the cases where multi-threading is enabled and when it is not. There’s no reason to do the same in your own code, really.

Makes sense, thanks for the clarification!

Sometimes I create transformed parameters in the partial sum function that are the length of start:end. Then if you do for (i in start:end), you want a new index to get into those shorter transformed parameter, e.g., int ii = i - start + 1.