为什么在编译时确定位置? [英] Why is locality determined at compile time?

查看:54
本文介绍了为什么在编译时确定位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的一点跟进.

  1. 为什么局部性是在编译时而不是在执行时确定的?纯粹是为了性能吗?
  2. 是否有在执行时查找变量的语言?IE.每次访问一个变量时,都会先在本地范围内搜索这个变量,然后在所有封闭范围内搜索?
  3. ECMA 语言如何处理这个问题?

换句话说,问题 2 是否存在以下代码(以必要的语法)起作用的语言:

To put question 2 in other words: Are there languages where the following code (in the necessary syntax) works:

def f(): print ('f')

def g():
    f()
    f = 42

g()

推荐答案

这种行为称为词法范围.您在 #2 中描述的内容称为动态范围,尽管口头描述具有误导性(您说封闭范围",其中调用函数"或激活记录"会更准确).

This behaviour is called lexical scoping. What you describe in #2 is called dynamic scoping, though the verbal description is misleading (you say "enclosing scopes" where "calling functions" or "activation records" would be more accurate).

实际上每种常用语言都使用词法范围,而不仅仅是 Python.这包括 C# 和 ECMAScript/JavaScript(除了 evalwith),我认为这就是ECMA 语言"的意思.已经有语言,其中一些仍在使用.Emacs Lisp 就是其中之一,Perl 提供词法和动态范围.

Virtually every language in common use uses lexical scoping, not just Python. That includes C# and ECMAScript/JavaScript (barring eval and with), which I assume is what you mean by "ECMA languages". There have been languages, and some of them are still in use. Emacs Lisp is one, and Perl offers both lexical and dynamic scoping.

词法范围的基本原理不仅仅是为了性能(包括闭包在内的完整词法范围实际上具有性能成本,请参阅 funcarg 问题),它是为了简单性和可靠性.虽然第一次学习这门语言时可能会令人惊讶,但规则实际上非常简单,因此有经验的程序员可以立即分辨出标识符的哪个使用指的是哪个范围.人们可以孤立地理解函数,因为执行不受谁调用该函数以及他们如何决定为他们的变量命名的影响.

The rationale for lexical scoping is not just for performance (full lexical scoping including closures actually has a performance cost, see the funcarg problems), it's for simplicity and reliability. While it may be surprising when first learning the language, the rules are actually dead simple so an experienced programmer can instantly tell which use of an identifier refers to which scope. One can understand functions in isolation, as execution isn't affected by who calls this functions and how they decided to name their variables.

这篇关于为什么在编译时确定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆