Syntax of if-else

I have not been able to find a full statement of the syntax for if-else. My observation is that only certain kinds of statements are allowed after if, but what are they?
If I write this user-defined function

functions{
 real mre(real x) {
   real y;
    if(x < 0) 
      y = -1;
    else 
      y = 1;
    return(y); 
  }
}

then it parses.

But if I write this:

functions{
 real mre(real x) {
   real y;
    if(x < 0) 
      print(y);
    else 
      y = 1;
    return(y); 
  }
}


I get:

SYNTAX ERROR, MESSAGE(S) FROM PARSER:
Variable "else" does not exist.
 error in 'modelaef6c7c5a76_mre' at line 6, column 8
  -------------------------------------------------
     4:     if(x < 0) 
     5:       print(y);
     6:     else 
               ^
     7:       y = 1;
  -------------------------------------------------

In my real life function I want to reject() if a certain variable is negative, but return it if it is positive. it appears that reject is not allowed after if.

Where is this syntax defined, please?

1 Like

Those are supposed to work but Stan 2.19 compiler has some bugs related to statements that are function calls. These have been fixed in the newest compiler.

You can always wrap the if-body in curly braces { }

functions{
 real mre(real x) {
   real y;
    if(x < 0) { 
      print(y);
    }
    else {
      y = 1;
    }
    return(y); 
  }
}
2 Likes

Many thanks. It is good, in a way, that it is a bug in Stan and not in me. I am using rstan 2.19.3, but I understand you to be saying that it is not the newest compiler.

braces sorts it for now.
Thanks again.

1 Like

If you’re interested in trying the latest compiler from R then you could try out the new CmdStanR interface. It’s always slow getting an RStan release through to CRAN, so RStan is always behind the latest Stan release, but CmdStanR runs CmdStan for you behind the scenes so it can use the latest version of Stan (or even experimental branches, whichever version of CmdStan you want). It hasn’t been officially released yet (coming soon) but it’s definitely usable and pretty stable and people been using it successfully for a while now:

1 Like