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.)
source
share