首页 > 解决方案 > 在 R 函数中模拟静态变量

问题描述

我正在寻找在 R 函数中模拟“静态”变量的方法。(我知道 R 不是一种编译语言……因此是引号。)对于“静态”,我的意思是“静态”变量应该是持久的,与函数相关联并且可以在函数内部进行修改。

我的主要想法是使用该attr功能:

# f.r

f <- function() {
  # Initialize static variable.
  if (is.null(attr(f, 'static'))) attr(f, 'static') <<- 0L

  # Use and/or modify the static variable...
  attr(f, 'static') <<- attr(f, 'static') + 1L

  # return something...
  NULL
}

这很好用,只要attr能找到f. 在某些情况下,情况不再如此。例如:

sys.source('f.r', envir = (e <- new.env()))
environment(e$f) <- .GlobalEnv
e$f() # Error in e$f() : object 'f' not found

理想情况下,我会在from attrinside 的“指针”上使用。并想到,但我不知道如何将这些功能与.ffsys.function()sys.call()attr

关于如何在 R 函数中模拟“静态”变量的任何想法或更好的设计模式?

标签: rstatic

解决方案


f像这样定义local

f <- local({ 
  static <- 0
  function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2

推荐阅读