gpt4 book ai didi

r - 理解 R 中的词法作用域

转载 作者:行者123 更新时间:2023-12-03 13:56:18 24 4
gpt4 key购买 nike

我正在阅读 this paper ( ungated copy )关于评估 R 编程语言的设计,并且无法理解有关词法范围(或没有词法范围)的特定示例。

在第 4 页,作者提供了以下使用 with 的示例。功能:

with(formaldehyde, carb*optden)

他们接着说:

The astute reader will have noticed that the above example clashes with our claim that R is lexically scoped. As is often the case, R is lexically scoped up to the point it is not. R is above all a dynamic language with full reflective access to the running program’s data and representation. In the above example, the implementation of with sidesteps lexical scoping by reflectively manipulating the environment. This is done by a combination of lazy evaluation, dynamic name lookup, and the ability turn code into text and back:


with.default <- function(env, expr, ...)
eval(substitute(expr),env, enclose=parent.frame())

The function uses substitute to retrieve the unevaluated parse tree of its second argument, then evaluates it with eval in the environment constituted by composing the first argument with the lexically enclosing environment. The ‘...’ is used to discard any additional arguments.



with的使用情况如何在这种情况下函数是否违反了词法作用域的原则?

最佳答案

通常在 R 词法范围的上下文中讨论时,意味着在函数的父环境中查找函数中的自由变量(即在函数中使用但未在函数中定义的变量),而不是在调用者(也称为父框架),但 with.default 中没有自由变量所以这个例子并没有说明在这个意义上违反了词法作用域。

例如,这说明了词法作用域:

x <- 1
f <- function() x
g <- function() { x <- 0; f() }
g() # 1

答案是 1,因为 1 是在 f 的环境中定义的。定义在。如果 R 使用动态作用域而不是词法作用域,答案将是 0(使用调用者的环境)。我们可以说明 R 如何模拟动态作用域,如下所示:
f <- function() eval.parent(quote(x))
g() # 0

添加:

在下面的评论中,@hadley 建议作者可能指的是 with.default 的第二个实际参数。没有在词汇上进行评估,这种解释似乎很可能。 with.default 的第二个实际参数不是相对于周围的词法环境进行评估的。读入 with.default作为表达式使用 substitute然后使用 eval 相对于第一个参数进行评估.有一些关于词法作用域的定义应该是什么的问题,因为即使在广泛讨论时也很少定义它,但与 R 相关的典型讨论将其称为对自由变量的处理。参见示例 Gentleman & Ihaka .

关于r - 理解 R 中的词法作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com