Lexical Scoping 和 Dynamic Scoping

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的这篇文章

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值