» R 中的词汇作用域

R 中的词汇作用域

1980
  • Gerald Jay Sussman
  • Guy L. Steele Jr.
Computer programmer demonstrating lexical scoping in R programming language.

R 使用词法作用域,这是从 Scheme 语言继承而来的概念。这意味着函数中自由变量的值是通过在函数定义环境中而不是调用环境中查找来解析的。这使得函数行为更加可预测,并且不受调用上下文的影响,这是函数式编程的一个关键特性。

Lexical scoping, also known as static scoping, is a fundamental convention for looking up variable names in a 编程语言. In R, when a function needs to access a variable that is not defined locally (a “free variable”), it searches for that variable in the environment where the function was created. This “creation environment” is permanently attached to the function. This contrasts with dynamic scoping, used in some older languages, where the search would proceed up the chain of function calls (the “calling environment”).

For example, consider a function `f()` that uses a variable `x` but doesn’t define it. If `f()` is defined in the global environment where `x` is 10, then no matter where `f()` is called from, it will always use `x = 10`. Even if it’s called from another function that has its own local `x = 20`, `f()` will ignore the calling environment’s `x` and use the one from its definition environment. This behavior makes code easier to debug and reason about, as a function’s behavior is determined solely by its own code and the environment in which it was defined.

This feature is crucial for functional programming paradigms, enabling powerful constructs like closures, where a function can “remember” the environment in which it was created. This is heavily utilized in advanced R programming and package development, such as in the `lapply` family of functions and in frameworks like Shiny for web applications.

UNESCO Nomenclature: 1203
- 计算机科学

类型

抽象系统

中断

递增

使用方法

广泛使用

前体

  • 编程语言中的作用域概念
  • Lisp 编程语言及其方言
  • Scheme 编程语言,它普及了词法作用域
  • Lambda 演算作为函数和作用域的理论基础

应用

  • 在 R 中创建闭包用于函数式编程
  • 开发包命名空间以避免变量冲突
  • 启用 dplyr 等软件包中使用的非标准评估技术
  • 构建无副作用的健壮且模块化的代码

专利:

    潜在的创新想法

    级别需要会员

    您必须是!!等级!!会员才能访问此内容。

    立即加入

    已经是会员? 在此登录
    Related to: lexical scoping, static scoping, functional programming, R, Scheme, environment, closure, free variable, namespace, non-standard evaluation.

    发表回复

    您的邮箱地址不会被公开。 必填项已用 * 标注

    迎接新挑战
    机械工程师、项目、工艺工程师或研发经理
    有效的产品开发

    可在短时间内接受新的挑战。
    通过 LinkedIn 联系我
    塑料金属电子集成、成本设计、GMP、人体工程学、中高容量设备和耗材、精益制造、受监管行业、CE 和 FDA、CAD、Solidworks、精益西格玛黑带、医疗 ISO 13485

    我们正在寻找新的赞助商

     

    您的公司或机构从事技术、科学或研究吗?
    > 给我们发送消息 <

    接收所有新文章
    免费,无垃圾邮件,电子邮件不分发也不转售

    或者您可以免费获得完整会员资格以访问所有受限制的内容>这里<

    历史背景

    (如果日期不详或不相关,例如 "流体力学",则对其显著出现的时间作了四舍五入的估计)。

    相关发明、创新和技术原理

    滚动至顶部

    你可能还喜欢