r - Function with extra parameters from another function's input -


this relatively problem i'm stumped. programming in r, don't think problem restricted r. below i've tried write simple code demonstrating problem:

f1 = function(x) {   return(a + x) }  f2 = function(ftn) {   return(ftn(1)) }  f3 = function(a) {   return(f2(f1)) } 

the problem: if call f3(2) [for example], f2(f1) returned, , f2(f1) returns f1(a+1). f1 not recognize value of 'a' put in f3, code doesn't work! there way can make f1 recognizes input f3?

r uses lexical scope, not dynamic scope. functions free variables (variables used not defined within them) in environment in function defined. f1 defined in global environment a looked in global environment , there no a there. can force f1 free variables in running instance of f3 this:

f3 = function(a) {   environment(f1) <- environment()   return(f2(f1)) } 

this temporarily creates new f1 within f3 desired environment.

another possibility if f1 needed within f3 define f1 there (rather in global environment):

f3 = function(a) {    f1 = function(x) {         return(a + x)   }         return(f2(f1)) } 

by way, last expression evaluated in running function returned written:

f3 <- function(a) {       f1 <- function(x) + x       f2(f1) } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -