Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if {...} else {...} : Does the line break between "}" and "else" really matters?

Tags:

r

if-statement

I write my if {...} else {...} statement in R in the following way as I find it more readable.

Testifelse = function(number1)
{
     if(number1>1 & number1<=5)
     {
          number1 =1
     }
     else if ((number1>5 & number1 < 10))
     {
          number1 =2
     }
     else
     {
          number1 =3
     }

     return(number1)
}

According to ?Control:

... In particular, you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source ...

the function above will cause syntax error, but actually it works! What's going on here?

Thanks for your help.

like image 730
Fredkho Avatar asked Jun 20 '16 18:06

Fredkho


1 Answers

Original question and answer

If we put in R console:

if (1 > 0) {
  cat("1\n");
  }
else {
  cat("0\n");
  }

why does it not work?

R is an interpreted language, so R code is parsed line by line. (Remark by @JohnColeman: This judgement is too broad. Any modern interpreter does some parsing, and an interpreted language like Python has no problem analogous to R's problem here. It is a design decision that the makers of R made, but it wasn't a decision that was forced on them in virtue of the fact that it is interpreted (though doubtless it made the interpreter somewhat easier to write).)

Since

if (1 > 0) {
  cat("1\n");
  }

makes a complete, legal statement, the parser will treat it as a complete code block. Then, the following

else {
  cat("0\n");
  }

will run into error, as it is seen as a new code block, while there is no control statement starting with else.

Therefore, we really should do:

if (1 > 0) {
  cat("1\n");
  } else {
  cat("0\n");
  }

so that the parser will have no difficulty in identifying them as a whole block.

In compiled language like C, there is no such issue. Because at compilation time, the compiler can "see" all lines of your code.


Final update related to what's going on inside a function

There is really no magic here! The key is the use of {} to manually indicate a code block. We all know that in R,

{statement_1; statement_2; ...; statement_n;}

is treated as a single expression, whose value is statement_n.

Now, let's do:

{
  if (1 > 0) {
    cat("1\n");
    }
  else {
    cat("0\n");
    }
}

It works and prints 1.

Here, the outer {} is a hint to the parser that everything inside is a single expression, so parsing and interpreting should not terminate till reaching the final }. This is exactly what happens in a function, as a function body has {}.

like image 77
Zheyuan Li Avatar answered Nov 15 '22 19:11

Zheyuan Li