r - 在 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 attr
inside 的“指针”上使用。并想到,但我不知道如何将这些功能与.f
f
sys.function()
sys.call()
attr
关于如何在 R 函数中模拟“静态”变量的任何想法或更好的设计模式?
解决方案
f
像这样定义local
:
f <- local({
static <- 0
function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2
推荐阅读
- nginx - 基于http_referrer的Nginx代理
- java - spring websocket 无法建立连接
- google-apps-script - 我需要使用 Google Apps 脚本反转选定的幻灯片顺序
- javascript - Firestore 验证日期(参数“秒”的值必须在 [-62135596800, 253402300799] 范围内)
- python - 查看 PySpark 脚本的 Glue 作业输出的最佳方式
- javascript - 使用 javascript 读取 Excel 文件并将其存储在数组中
- powershell - 获取 SharePoint Online 术语集并在 PowerShell 中不存在时创建术语
- php - 由于用户的变化,如何在 woocommerce 中更改购物车页面?
- vb.net - 如何使用 Ref 游标调用 Oracle 函数并在 Visual Basic 上返回值
- visual-studio-code - VS Code 远程服务器扩展显示“正在尝试重新连接”