static scoping and dynamic scoping

Static Scoping:

With static scope, a variable always refers to its top-level environment. This is a property
of the program text and unrelated to the runtime call stack. Because matching a variable 
to its binding only requires analysis of the program text, this type of scoping is sometimes 
also called lexical scoping. Static scope is standard in modern functional languages such as 
ML because it allows the programmer to reason as if variable bindings are carried out by
substitution.


Static scoping also makes it much easier to make modular code and reason about it, since 
its binding structure can be understood in isolation. In contrast, dynamic scope forces the 
programmer to anticipate all possible dynamic contexts in which the module's code may
be invoked.


In other words, a language uses static scope or lexical scope if it is possible to determine 
the scope of a declaration by looking only at the program. Otherwise, the language uses
dynamic scope


Dynamic Scoping:

With dynamic scope, each identifier has a global stack of bindings. Introducing a local
variable with name x pushes a binding onto the global x stack (which may have been 
empty), which is popped off when the control flow leaves the scope. Evaluating x in any 
context always yields the top binding. In other words, a global identifier refers to the 
identifier associated with the most recent environment. Note that this cannot be done at 
compile time because the binding stack only exists at runtime
, which is why this type of
scoping is called dynamic scoping.


Static Scope:

$x = 100;


sub foo()
{
my $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
my $x = 20;
hoo();
}


sub hoo()
{
my $x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";

输出结果:

the second x is: 30

the first x is:10

the third one is: 100



$x = 100;


sub foo()
{
my $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
$x = 20;
hoo();
}


sub hoo()
{
$x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";


输出结果:

the second x is: 30

the first x is:10

the third one is: 30




Dynamic Scope:

$x = 100;


sub foo()
{
local $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
$x = 20;
hoo();
}


sub hoo()
{
$x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";

输出结果:

the second x is: 30

the first x is:30

the third one is: 100



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值