Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop function evaluation using another function in R

Tags:

r

evaluation

I did a test with nested return function in R, but without success. I came from Mathematica, where this code works well. Here is a toy code:

fstop <- function(x){
  if(x>0) return(return("Positive Number"))
}

f <- function(x){
  fstop(x)
  "Negative or Zero Number"
}

If I evaluate f(1), I get:

[1] "Negative or Zero Number"

When I expected just:

[1] "Positive Number"

The question is: there is some non-standard evaluation I can do in fstop, so I can have just fstop result, without change f function?

PS: I know I can put the if direct inside f, but in my real case the structure is not so simple, and this structure would make my code simpler.

like image 420
Murta Avatar asked Dec 25 '22 08:12

Murta


1 Answers

Going to stick my neck out and say...

No.

Making a function return not to its caller but to its caller's caller would involve changing its execution context. This is how things like return and other control-flow things are implemented in the source. See:

https://github.com/wch/r-source/blob/trunk/src/main/context.c

Now, I don't think R level code has access to execution contexts like this. Maybe you could write some C level code that could do it, but its not clear. You could always write a do_return_return function in the style of do_return in eval.c and build a custom version of R... Its not worth it.

So the answer is most likely "no".

like image 76
Spacedman Avatar answered Jan 09 '23 00:01

Spacedman