LangDev

Dynamic Scope

mithrandir

전 여태까지 클로져라거나, 혹은 실행중에 변수이름을 심볼테이블에서 가져오는게 dynamic scope라고 생각했는데, 그게 착각이었군요.

아시는 분들이 더 많겠지만, 만약 다음과 같은 코드에서(C코드긴 한데, C라고 생각하지 말고 보세요)

int a=1;

int func1()
{
  int a=3;
  func2();
}

int func2()
{
  printf("%d\n", a);
}

int main()
{
  func1();
}

일때 1이 출력되면 static scoping, 3이 출력되면 dynamic scoping이에요. LISP의 창시자 McCarthy도 처음에 LISP을 dynamic scope라 짰다가 그걸 버그로 인정했다는군요.

예전 펄은 dynamic scoping이었다는데, 정말 그런지 궁금합니다.

혹 그밖에 dynamic scoping을 채택하고 실존하고 있는 언어가 있다면 알려주세요~

제가 중학교 때쯤인가, JavaScript의 함수가 클로져라는 것을 모르고 Dynamic Scope겠거니 하며 삽질한 적이 있어요. 클로져라는 걸 알았으면 훨씬 쉽게 해결했을텐데;

홍민희

위키백과의 해당 항목을 읽어보니 Perl의 경우를 잘 설명하고 있네요. Perl에서는 클로져(lexical closure)에 해당하는 변수 선언을 my로 하고, 동적 범위(dynamic scope)에 해당하는 변수 선언을 local로 한다고 합니다.

In the language Perl, variables can be defined with either lexical or dynamic scoping. Perl's keyword my defines a lexically scoped local variable, while the keyword local defines dynamically scoped local variable.1 This allows for further clarification with practical examples of each scoping model.

$x = 0;
sub f { return $x; }
sub g { my $x = 1; return f(); }
print g()."\n";

The example above uses my for static, also called lexical, scoping of g's local variable $x. As above, calling g returns 0 because f cannot see g's variable $x, so it looks for the global $x.

$x = 0;
sub f { return $x; }
sub g { local $x = 1; return f(); }
print g()."\n";

In this alternative, local is used to make g's $x dynamically-scoped. Now, calling g yields 1 because f sees g's local variable by looking up the execution stack.

In other words, the dynamically-scoped variable $x is resolved in the environment of execution, rather than the environment of definition.

홍민희

대부분의 스크립트 언어가 dynamic scope를 사용할텐데요..

sylphong

어떤 예가 있을까요? 잘 생각이 안나요.

적어도 루비는 아니거든요.

mithrandir

제가 아는 언어 중에서는 없네요. Python, Ruby, JavaScript 등도 모두 lexical closure이고...

홍민희

python이 dynamic scope인줄 알고있었는데..아닌가보군요.. elisp은 dynamic scope써요..

sylphong