静态和动态作用域 [英] statically and dynamically scopes

查看:151
本文介绍了静态和动态作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理这个问题,我得到了答案:



静态:20,16



Dynamically:20,100



是否正确?



下面(用Pascal语言)。
语言的输出是静态范围的?如果语言是动态作用域,输出是什么?

 程序main; 
x:integer;
过程f1(z:integer)
begin
return z * x;
end
过程f2(z:integer)
int x;
begin
x = 2;
return f1(z)* x;
end

begin / *主程序* /
x = 5;
print f1(4);
print f2(4);
end


解决方案

?使用静态范围的Perl:

  my $ x = 5; 
sub f1($){
my $ z = shift;
return $ z * $ x;
}
sub f2($){
my $ z = shift;
my $ x = 2;
return f1($ z)* $ x;
}
print f1(4),\\\
;
print f2(4),\\\
;

我得到 20 40 。 ( 20 4 * 5 40 c $ c>(4 * 5)* 2 。)



取代所有 my local s获取动态范围,我得到 20 16 。 ( 20 4 * 5 16 不幸的是,由于你只是发表了你的结论,没有解释,我可以''' t指出你在哪里错了。 。 。


I'm working on this problem and I got the answers :

Statically: 20, 16

Dynamically: 20, 100

is that correct?

Consider the program below (in a Pascal like language). What is the output of the language is statically scoped? What is the output if the language is dynamically scoped?

Program main;
   x: integer;
procedure f1(z: integer)
begin 
       return z * x;
   end
procedure f2(z: integer)
      int x;
   begin
       x = 2;
       return f1(z)  * x;
   end

begin /* main program */
   x = 5;
print f1(4);
   print f2(4);
end

解决方案

Why not try out both versions? Using Perl with static scope:

my $x = 5;
sub f1($) {
  my $z = shift;
  return $z * $x;
}
sub f2($) {
  my $z = shift;
  my $x = 2;
  return f1($z) * $x;
}
print f1(4), "\n";
print f2(4), "\n";

I get 20, 40. (20 being 4 * 5, 40 being (4 * 5) * 2.)

Replacing all the mys with locals to get dynamic scope, I get 20, 16. (20 being 4 * 5, 16 being (4 * 2) * 2.)

Unfortunately, since you only posted your conclusions, no explanation, I can't point out where you went wrong . . .

这篇关于静态和动态作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆