Lexical Scoping 和 Dynamic Scoping

来源:互联网 发布:网络市场监管 编辑:程序博客网 时间:2024/06/08 18:33

Lexical Scoping 和 Dynamic Scoping
A name that is lexically bound is looked up only in bindings in the lexical environment of the name – that is, in bindings that enclose the name in the source code. When there are multiple bindings in the lexical environment, the innermost one is used.
只是在距离被调用代码最近的环境中去找,如果有多个环境的话,从最里面的环境先找

A name that is dynamically bound is looked up only in bindings in the dynamic environment of the name – that is, in all bindings which have been created since the program began and which have not yet been destroyed. When there are multiple bindings in the dynamic environment, the most recently created one is used.
在从程序启动到现在创建的还没有销毁的环境中去找,找的顺序是按时间序去找(从最新被创建的环境开始)

https://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding

(let ((x 2))                        ; bind 1  (let ((f (lambda (y) (* x y))))   ; define a closure with (bind 1)     (let ((x 4))                    ; bind 2      (f 3))))

现在的问题是f函数中的自由变量x从bind 1中获得还是从bind 2中获得?
如果是Lexical scoping的语言的话,在声明lambda的时候,会将当前的环境也就是bind 1保存一份新的环境,假设叫做env-save,当你调用函数f的时候,自由变量会从env-save中查找,又因为这个保存起来的环境和当前执行的环境不相互影响,所以被称之为闭包。所以输出是:2*3 = 6

如果是Dynamic scoping的语言的话,对函数f中的自由变量,程序会从离自己最近的环境中去找它的值,最近的是bind 2,所以输出是:4*3 = 12

实在不懂的话,可以看看yinwang的这篇文章

原创粉丝点击