 # Why operator function not work?

I put a function `if_greater` in the `functions` block like this:

`````` functions {
vector if_greater(vector x, vector y) {
int n;
vector[n] D;
n = rows(x);
for (i in 1:n){
D[i] = operator>(x[i],y[i]) ;
}
return D;
}

``````

An error popped up and pointed to the `operator>` function. I changed it to the conditional operator function ` x[i] > y[i] ? 1:0` and it works!

I looked up the reference manual. the `operator` function can be used in this way. So I wonder why the error occurred. Thanks.

The entire function would be better written as

``````functions {
vector if_greater(vector x, vector y) {
int n = rows(x);
vector[n] D;
if (rows(y) != n) reject("rows of x and y must match");
for (i in 1:n) D[i] = x[i] > y[i];
return D;
}
}
``````

I think there’s some confusion here about what `operator` means, which is totally understandable if you’re not used to that terminology. `operator` isn’t the name of a function, it’s a term used to describe the type of construct that `>` is, which is basically a function that behaves differently semantically than regular functions (https://en.wikipedia.org/wiki/Operator_(computer_programming)). In other words, describing `>` as an operator is intended to convey that the syntax to use it is `x > y` rather than `>(x,y)`, which would be the standard way to call regular functions. Anyway, you can just use @bgoodri’s version of the function, but to get your original version to not error you’d need to replace `operator>(x[i],y[i])` with just `x[i] > y[i]`. Hope that helps clarify.

1 Like