返回函数的R函数。。。和可变范围
我正在学习返回其他函数的函数。例如:返回函数的R函数。。。和可变范围,r,R,我正在学习返回其他函数的函数。例如: foo1 <- function() { bar1 <- function() { return(constant) } } foo2 <- function() { constant <- 1 bar2 <- function() { return(constant) } } > constant <- 2 > f1() [1] 2 > f2() [1]
foo1 <- function()
{
bar1 <- function()
{
return(constant)
}
}
foo2 <- function()
{
constant <- 1
bar2 <- function()
{
return(constant)
}
}
> constant <- 2
> f1()
[1] 2
> f2()
[1] 1
然后,它们似乎具有相同的函数定义:
> f1
function()
{
return(constant)
}
<environment: 0x408f048>
> f2
function()
{
return(constant)
}
<environment: 0x4046d78>
>
>f1
函数()
{
返回(常数)
}
>f2
函数()
{
返回(常数)
}
>
但这两种功能是不同的。例如:
foo1 <- function()
{
bar1 <- function()
{
return(constant)
}
}
foo2 <- function()
{
constant <- 1
bar2 <- function()
{
return(constant)
}
}
> constant <- 2
> f1()
[1] 2
> f2()
[1] 1
>常数f1()
[1] 2
>f2()
[1] 1
我的问题:为什么具有相同函数定义的两个函数产生不同的结果是合法的?
我知道foo1
将常量视为全局变量,而foo2
视为常量变量,但无法从函数定义中明确区分这一点
(我可能遗漏了一些基本的东西。)当然它们不同,环境也不同。尝试
ls(环境(f1))
然后ls(环境(f2))
然后获取('constant',环境(f1))
,对于f2
列夫的回答是正确的。更详细地描述。调用f1或传递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()
#因为R是解释的。。变量常量不必在词汇环境中定义。。。所有这些都会在运行时进行检查和评估
foo1returnedthis函数Trylibrary(pryr);不封闭(f1);取消关闭(f2)
。我希望你读到你声称它们完全相同的说法是不正确的。