问题描述
根据我的编程语言课,在一个使用词法范围
函数体在环境中被评估定义的是函数,而不是调用函数的环境.
例如,SML 遵循以下行为:
For example, SML follows this behavior:
val x = 1
fun myfun () =
x
val x = 10
val res = myfun() (* res is 1 since x = 1 when myfun is defined *)
另一方面,Python 不遵循这种行为:
On the other hand, Python does not follow this behavior:
x = 1
def myfun():
return x
x = 10
myfun() # 10 since x = 10 when myfun is called
那么为什么 Python 被描述为使用词法范围?
So why is Python described as using lexical scoping?
推荐答案
除了@abarnert 和@user2357112 的回复之外,它可能会帮助您考虑 Python 代码的 SML 等效项:
In addition to the responses of @abarnert and @user2357112, it may help you to consider an SML equivalent of the Python code:
val x = ref 1
fun myfun () = !x
val () = x := 10
val res = myfun ()
第一行声明了一个变量 x
,它引用一个整数并将引用的单元格设置为 1.函数体取消引用 x
以返回引用单元格中的值.第三行将引用的单元格设置为 10.第四行中的函数调用现在返回 10.
The first line declares a variable x
that references an integer and sets the referenced cell to 1. The function body dereferences x
to return the value in the referenced cell. The third line sets the referenced cell to 10. The function call in the fourth line now returns 10.
我使用了笨拙的 val () = _
语法来修复排序.添加声明只是为了它对 x
的副作用.也可以写成:
I used the awkward val () = _
syntax to fix an ordering. The declaration is added solely for its side effect on x
. It is also possible to write:
val x = ref 1
fun myfun () = !x;
x := 10;
val res = myfun ()
环境是不可变的——特别是 x
总是指向同一个内存单元——但一些数据结构(参考单元和数组)是可变的.
The environment is immutable—notably x
always points to the same memory cell—but some data structures (reference cells and arrays) are mutable.
这篇关于Python 范围规则是否符合词法范围的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!