HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

When are Dynamic and Lexical Scoping equivalent?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
lexicalequivalentarescopingdynamicandwhen

Problem

I am designing a small DSL and I know that implementing dynamic scoping (with a simple global stack) is easier then using full lexical scoping (each function needs its own scope/closure). What kind of features can be added that do not care how scope is implemented and what features would require a particular kind of scope implementation?

For example, if I have a very simple language that does not allow nested functions or function arguments I feel that both implementation choices are likely equivalent. On the other end of the spectrum, if I wanted to support returning inner functions then I'm pretty sure we would need to allow functions to save their own closures. However, I am not really sure what would happen in the middle if say, I alowed nested functions while not allowing them to be returned or if I allowed functions to be passed as arguments to other functions.

Solution

If you allow one function to call another, then you have enough power to distinguish a lexically defined variable from a dynamically defined one.

def scope {
  var x = 10
  def f() {
    return g()
  }
}
def g() {
  return x;
}
scope.f()


If x is dynamically scoped, the code returns 10. If it is lexically defined, the result is an error.

Thus if you want a language where dynamic and lexical scoping behave the same, it will be a rather weak language.

Code Snippets

def scope {
  var x = 10
  def f() {
    return g()
  }
}
def g() {
  return x;
}
scope.f()

Context

StackExchange Computer Science Q#4670, answer score: 7

Revisions (0)

No revisions yet.