我正在学习返回其他功能的函数.例如:
foo1 <- function()
{
bar1 <- function()
{
return(constant)
}
}
foo2 <- function()
{
constant <- 1
bar2 <- function()
{
return(constant)
}
}
Run Code Online (Sandbox Code Playgroud)
假设,现在,我声明函数f1,f2如下所示:
constant <- 2
f1 <- foo1()
f2 <- foo2()
Run Code Online (Sandbox Code Playgroud)
然后看起来它们具有相同的功能定义:
> f1
function()
{
return(constant)
}
<environment: 0x408f048>
> f2
function()
{
return(constant)
}
<environment: 0x4046d78>
>
Run Code Online (Sandbox Code Playgroud)
但这两个功能是不同的.例如:
> constant <- 2
> f1()
[1] 2
> f2()
[1] 1
Run Code Online (Sandbox Code Playgroud)
我的问题:为什么两个具有相同函数定义的函数产生不同的结果是合法的?
我理解foo1将常量视为全局变量和foo2常量变量,但是不可能从函数定义中确定这一点吗?
(我可能遗漏了一些基本的东西.)
当然它们是不同的,环境是不同的.尝试ls(environment(f1))然后ls(environment(f2))然后get('constant', environment (f1))和相同f2
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |