递归函数和全局变量与局部变量

标签 r recursion global-variables local-variables

我正在用 R 编写一个递归函数,我希望它修改一个全局变量,以便我知道调用了多少个函数实例。我不明白为什么以下不起作用:

i <- 1

testfun <- function( depth= 0 ) {

  i <- i + 1
  cat( sprintf( "i= %d, depth= %d\n", i, depth ) )
  if( depth < 10 ) testfun( depth + 1 )
}

这是输出:
i= 2, depth= 0
i= 2, depth= 1
i= 2, depth= 2
i= 2, depth= 3
i= 2, depth= 4
i= 2, depth= 5
i= 2, depth= 6
i= 2, depth= 7
i= 2, depth= 8
i= 2, depth= 9
i= 2, depth= 10

这是预期的输出:
i=2, depth= 0
i=3, depth= 1
i=4, depth= 2
i=5, depth= 3
i=6, depth= 4
i=7, depth= 5
i=8, depth= 6
i=9, depth= 7
i=10, depth= 8
i=11, depth= 9
i=12, depth= 10

最佳答案

您可以使用 local 函数来做同样的事情,但不修改全局环境:

testfun <- local({
  i <- 1
  function( depth= 0 ) {
    i <<- i + 1
    cat( sprintf( "i= %d, depth= %d\n", i, depth ) )
    if( depth < 10 ) testfun( depth + 1 )
  }
})

这非常巧妙地将 testfun 函数包装在包含 i 的本地环境中。这种方法在提交 CRAN 的包中应该是可以接受的,而修改全局环境则不是。

关于递归函数和全局变量与局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16480722/

相关文章:

algorithm - 算法中的pass是什么意思?

ruby - 如何在 Ruby 中编写递归阶乘函数?

global-variables - 计算 NetLogo 中变量的不同值的数量

项目中的 C++ 全局常量

r - 按列将多个函数应用于两个数据框

r - 带有突出显示的国家和选定城市的简单世界地图

r - 从循环创建数据框

regex - 字符串中除 `in` , `the` `of` 之外的每个单词的首字母大写

c - 这个 C int 函数在没有 return 语句的情况下如何工作?

node.js - node-red 中的全局上下文用于存储 http req 和 res 对象