Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function which returns a function... and variable scope

Tags:

r

I am learning about functions returning other functions. For example:

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

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

Suppose, now, I declare functions f1 and f2 as follows:

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

Then it appears they have the same function definition:

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

BUT the two functions are different. For example:

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

My question: Why is it legal for two functions, with identical function definitions, to produce different results?

I understand that foo1 treats constant as a global variable and foo2 as a constant variable, but it is impossible to tell this from the function definition surely?

(I am probably missing something fundamental.)

like image 494
Kian Avatar asked Jan 09 '23 05:01

Kian


1 Answers

Sure they're different, the environments are different. Try ls(environment(f1)) and then ls(environment(f2)) and then get('constant', environment (f1)) and same for f2

like image 188
Lev Kuznetsov Avatar answered Jan 11 '23 17:01

Lev Kuznetsov