开发者

Closures and dynamic scope?

I think I understand why there is a danger in allowing closures in a language using dynamic scope. That is, it seems you will be able to close the variable OK, but when trying to read it you will only get the value at the top of global stack. This might be dangerous i开发者_开发百科f other functions use same name in the interim.

Have I missed some other subtlety?


I realize I'm years late answering this, but I just ran across this question while doing a web search and I wanted to correct some misinformation that is posted here.

"Closure" just means a callable object that contains both code and an environment that provides bindings for free variables within that code. That environment is usually a lexical environment, but there is no technical reason why it can't be a dynamic environment.

The trick is to close the code over the environment and not the particular values. This is what Lisp 1.5 did, and also what MACLisp did for "downward funargs."

You can see how Lisp 1.5 did this by reading the Lisp 1.5 manual at http://www.softwarepreservation.org/projects/LISP/book

Pay particular attention in Appendix B to how eval handles FUNCTION and how apply handles FUNARG.

You can get the basic flavor of programming using dynamic closures from http://c2.com/cgi/wiki?DynamicClosure

You can get an in depth introduction to the implementation issues from ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-199.pdf

Modern dynamically scoped languages generally use shallow binding, where the current value of each variable is kept in one global location, and function calls save old values away on the stack. One way of implementing dynamic closures with shallow binding is described at http://www.pipeline.com/~hbaker1/ShallowBinding.html


Yes, that's the basic problem. The term "closure" is short for "lexical closure", though, which by definition captures its lexical scope. I'd call the things in a dynamically scoped language something else, like LAMBDA. Lambdas are perfectly safe in a dynamically scoped language as long as you don't try to return them.

(For an interesting thought experiment, compare the problem of returning a dynamically scoped lambda in Emacs Lisp to the problem of returning a reference to a stack-allocated variable in C, and how both are impossible in Scheme.)

A long time ago, back when languages with dynamic scope were much less rare than today, this was known as the funargs problem. The problem you mention is the upward funargs problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜