views:

49

answers:

1

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?

+2  A: 

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.

Nathan Sanders
I won't edit the answer but: "Usually" is wrong -- closures are always "lexical closure", named this way because they close the expression over its lexical environment. As for lambdas being safe -- not being able to use lambdas as closures is hugely diminishing their value, but even without that, dynamic scope is inherently bad for your program's health since you can't be sure of the meaning of any binding.
Eli Barzilay
Thank you for the funargs link. I did never learn of this before.
Eli
@Eli Barzilay: You are right, I was being overly wishy-washy. I will remove 'usually'. As for general program health, I completely agree, but the question is not general. Like I said, dynamically scoped lambdas are about as safe as unrestricted pointers...
Nathan Sanders
@Eli: Probably the reason you never heard of the funargs problem is that it's quite old and almost all languages now use lexical scope in order to solve it. (Among other reasons.)
Nathan Sanders