【问题标题】:Emulating static variable within R functions在 R 函数中模拟静态变量
【发布时间】:2020-03-26 07:46:28
【问题描述】:

我正在寻找在 R 函数中模拟“static”变量的方法。 (我知道 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

理想情况下,我会在f 内的f 的“指针”上使用attrsys.function()sys.call() 浮现在脑海中,但我不知道如何将这些功能与 attr 一起使用。

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

【问题讨论】:

    标签: r static


    【解决方案1】:

    local 中定义f,如下所示:

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

    【讨论】:

    • 函子模式。如此明显。你是最棒的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    相关资源
    最近更新 更多