如何将嵌套函数的访问范围定义为全局?

时间:2012-12-07 09:02:42

标签: r nested-attributes

我的R代码如下:

func1 = function(a) {

  func2 = function(a) {
    return(a+2)
  }

  func3 = function(a) {
    return(a+3)
  }
  return(a+func2(a))
}

我是否有可能从func1外部调用func2或func3? 例如。我该怎么办:

x <- func2(10) #from the console?

2 个答案:

答案 0 :(得分:1)

你可以创建一个函数闭包:

##I've removed the brackets and return to shorten the function
func1 = function(a) {
  func2 = function(a) a+2
  func3 = function(a) a+3
  return(list(func2=func2, func3=func3))
}

您可以使用闭包来共享变量:

func1 = function(a) {
    a = a
    func2 = function() a + 2
    func3 = function() a + 3 
    return(list(func2=func2, func3=func3))
}

f = func1(50)
f$func2()
f$func3()

答案 1 :(得分:0)

不,你不能。

func2在func1的范围内定义。

但问题真的很模糊!任何netsed函数都可以访问全局范围。

a <- 10
function <- f(x){
   g <- function(y=x) x+a
   g(x)
}

这里函数g是嵌套的,并且有一个自由变量a。  解释器在g和f的范围内lokks,然后在f的本地帧中寻找a的值(全局)

为什么要将嵌套函数定义为嵌套函数,如果要将其作为全局函数进行访问?