static scoping and dynamic scoping

来源:互联网 发布:unity3d encodetojpg 编辑:程序博客网 时间:2024/06/07 09:23

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 0
原创粉丝点击