Suppose I want to have something like this in data
:
int n;
array[n] int a;
int s = sum(a);
vector[s] x;
vector[s] y;
But this is not possible, because assignment statements aren’t possible within data
.
I had in idea to instead do something like:
data {
int n;
array[n] int a;
int s; // redundant input
vector[s] x;
vector[s] y;
}
transformed data {
if (s != sum(a)) {fatal_error("does not add up!");}
}
another option would be
data {
int n;
array[n] int a;
vector[sum(a)] x;
vector[sum(a)] y;
}
transformed data {
int s = sum(a);
}
but both feel a little clunky and would also be inefficient if instead of the sum
was an expensive computation or I have to repeat the pattern many times over.
Would either of the options be considered more idiomatic/preferred for a good reason? Or is there a better way I don’t know of? Or maybe does an optimizer in the compiler recognize it’s a pure function and actually computes it only once?