R, which returns a function ... and a variable region

I will learn about functions that return other functions. For instance:

foo1 <- function()
{
  bar1 <- function()
  {
    return(constant)
  }
}

foo2 <- function()
{
  constant <- 1
  bar2 <- function()
  {
    return(constant)
  }
}

Suppose now declare the function f1and f2in the following way:

constant <- 2
f1 <- foo1()
f2 <- foo2()

Then it looks like they have the same function definition:

> f1
function()
  {
    return(constant)
  }
<environment: 0x408f048>
> f2
function()
  {
    return(constant)
  }
<environment: 0x4046d78>
> 

BUT two functions are different. For instance:

> constant <- 2
> f1()
[1] 2
> f2()
[1] 1

My question is: why is this legal for two functions with identical function definitions to get different results?

I understand that it foo1considers a constant as a global variable and foo2as a constant variable, but this is impossible to say from the definition of a function?

(I probably don't have something fundamental.)

+4
source share
2 answers

, , . ls(environment(f1)), ls(environment(f2)), get('constant', environment (f1)) f2

+7

R

. . f1 pass f1 , , .

#since R is interpreted.. the variable constant doesn't have to be defined in the lexical environment... this all gets checked and evaluated at runtime
foo1ReturnedThisFunction <- foo1() 
#outputs "Error in foo1ReturnedThisFunction() : object 'constant' not found"
foo1ReturnedThisFunction() 
#defined the variable constant in the lexical environment
constant <- 5 
#outputs 5
foo1ReturnedThisFunction() 

foo2... "" ( , ) , ""

+2

Source: https://habr.com/ru/post/1568454/


All Articles