【问题标题】:call arguments of for loop no matter how they are named调用 for 循环的参数,无论它们如何命名
【发布时间】:2021-12-09 07:09:04
【问题描述】:

是否可以在 for 循环中调用 minmax 和运行变量 i 而无需通过它们的名称专门引用这些对象?

以这个for循环为例

for(i in min:max) {
     # do some calculation
}

假设现在我有一个函数f,其参数为mimaii。然后,我想做

for(i in min:max) {
     # do some calculation
     f(mi, ma, ii)
}

mi = minma = maxi = ii 自动出现在哪里。也就是说,函数f 自动将minmaxi 作为输入,以从for 循环环境中访问它们。

我希望我说清楚了。但是,如果有任何令人困惑的地方,请告诉我,我会尝试进一步澄清。

谢谢!

【问题讨论】:

  • 您是在问是否可以在没有参数的情况下直接调用 f() 并让它从调用环境中推断出 minmaxi 的值?
  • mi 和 ma 需要动态吗?
  • 没错!实际上不,mi 和 ma 不需要是动态的!我的意思是,如果可以用动态 mi 和 ma 来实现它,那就太好了!
  • 可以的。我强烈反对它:它是草率的函数式编程,表明设计糟糕,容易受到各种困扰可重复性的问题的影响,故障排除可能是一项违反直觉的苦差事,以及......可能还有许多其他原因。一个函数应该只“知道”明确传递给它的东西;异常很少见,而且在元编程中通常非常有用,而不是像这样。
  • 不过,底线是,这很可能是一个诱人的想法(对于一个有点懒惰的交互式 R 工作),但在许多其他方面是一个非常糟糕的想法。

标签: r function loops for-loop


【解决方案1】:

在需要信息的for 之后立即致电forInfo它假定 for 语句本身在一行上表现得相当好,在定义边界的表达式中没有空格。

forInfo 的参数是:

  • 包含for的函数
  • 将被搜索的唯一字符串。它不能出现在函数的其他任何地方
  • 环境调用forInfo。默认值通常是正确的。

forInfo 的代码和一些测试如下。

library(gsubfn)

forInfo <- function(fun, mark, env = parent.frame()) {
    b <- format(body(fun))
    x <- strapplyc(b[grep(mark, b)-1], "\\S+") |>
      unlist() |>
      setdiff(c("for", "in", "{"))
    x[1] <- sub("^\\(", "", x[1])
    x[2] <- sub("\\)$", "", x[2])
    list(index = get(x[1], env),
         bounds = range(eval(parse(text = x[2]), env)))
}
   
# test - on each iteration display the value of index and the bounds

f <- function() {

  min <- 1; max <- 3
  for(i in min:max) {
    v <- forInfo(f, "mark1")
    with(v, cat("index:", index, "bounds:", bounds, "\n"))
  }      
  for(j in 13:15) {
    v <- forInfo(f, "mark2")
    with(v, cat("index:", index, "bounds:", bounds, "\n"))
  }
  for(k in head(letters)) {
    v <- forInfo(f, "mark3")
    with(v, cat("index:", index, "bounds:", bounds, "\n"))
  }
}

f()

给予:

index: 1 bounds: 1 3 
index: 2 bounds: 1 3 
index: 3 bounds: 1 3 
index: 13 bounds: 13 15 
index: 14 bounds: 13 15 
index: 15 bounds: 13 15 
index: a bounds: a f 
index: b bounds: a f 
index: c bounds: a f 
index: d bounds: a f 
index: e bounds: a f 
index: f bounds: a f 

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多