Why is the expression after the return bracket checked for lexical correctness, but not evaluated?

Consider the following code:

a = function() { return (23) } b = function() { return (23) * 23 } c = function() { return (23) * someUndefinedVariable } 

All of the above succeeds (if called) and return 23. I assumed that R ignores everything that happens after the return closing parenthesis, but this is actually not the case because this code does not work when loading the code:

 d = function() { return (23) something } 

My assumption is that in the last example, some lexers or parsers fail. But in the first expression it is parsed as (return(23))*some (because return treated as a function), but the evaluation stops at return , and therefore R does not try to find some .

Does this sound normal? This is the reason? Is this behavior expected? Can I include some warnings so that the interpreter tells me about such “inaccessible code”?

+7
r
source share
3 answers

This code failed:

 d = function() { return (23) something } 

... has nothing to do with the previous code and everything related to the impossibility of analysis: return (23) something . Unlike a previously erroneous attempt to redefine c that had a valid body / parsing element, body d cannot be placed in a functional form. The parser does not actually stop when returning (23), but after it tokens something and “understands” that it is not a semicolon or the name of the infix function. Thus, the R interpreter now has two expressions and there is no actual connector / separator between them.

Objects referenced by objects within the function body R during the definition are not evaluated or even checked for presence in the parameter list or outside the function. (R is not a compiler.)

+4
source share

R parses the operator before calculating it:

 parse(text = "funky <- function(x) { return(x) * dog }") 

returns:

 expression(funky <- function(x) { return(x) * dog }) 

but

 parse(text = "funky <- function(x) { return(x) dog }") 

returns:

 Error in parse(text = "funky <- function(x) {\n return(x) dog\n}") : <text>:2:19: unexpected symbol 1: funky <- function(x) { 2: return(x) dog ^ 

In the above example, although the dog variable does not exist (and appears after return ), R can still parse use it as the correct code.

+3
source share

return not just considered as a function, it is a function. And at any time, when it is called, the path to the code will exit any function that you are currently in.

Thus, this means that by the time R would have managed to multiply the result of return by 23, it will all end, this evaluation will stop, and there will be no error messages or warnings (like there is no warning or error when you return inside some if condition) .

While your last function simply cannot be parsed (which more or less means that the expression is placed in the function tree) and so that the function cannot be created.

+3
source share

All Articles