Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 if other functions use same name in the interim.

Have I missed some other subtlety?

like image 308
Eli Schneider Avatar asked Sep 10 '10 01:09

Eli Schneider


1 Answers

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

like image 174
Andru Luvisi Avatar answered Oct 05 '22 23:10

Andru Luvisi