views:

22

answers:

1

Imagine you are designing your own programming language. Very simple language for quite specific purpose. It has functions, loops and variables. And you want to make use of dynamic scoping for variables.

Consider the imaginary example:

var x = "foo"
var count = 0

loop (/* condition */) {

    var x = "bar"
    // A new stack frame is created for 'x',
    // so inside the loop (and any subsequent function calls) it is bound to "bar",
    // but outside the loop 'x' is still bound to "foo"

    print (x) // output is "bar"

    var count = count + 1
}

print (x) // output is "foo"
print (count) // desired output is something above zero, but it's not !!!

My question is - how to make 'count' variable value set inside the loop to be visible outside? How would you do that so it to look more natural (or less confusing) to the users?

  • Would you introduce a special keyword to assign a value to an existing variable from the outer scope in additional to the keyword to define a new variable in the current scope? Let's say set and var, or assing and def, etc. But what 'outer scope' would then mean? What if 'count' is not defined right before the loop but instead it is defined earlier somewhere in the invocation stack? Would "set count = ..." assign a value to the variable from that parent of parent of parent frame?
  • Would you introduce a return value (or tuple) to the loop statement, so that one could write something like:

    var count = 0 var count = loop (condition == true) returns [i] { var i = i + 1 }

Wouldn't that look awkward?

  • Your solution?

As far as know Perl supports the dynamic scoping using local keyword. How would you implement such example in Perl using dynamic scoped variables only?

Thank you!

A: 

Sounds like you want to have your cake and eat it too, here. Some variables declared in inner scope should "hide" identical vars in outer scope, while others should not.

Sounds pretty easy to me; if a variable is declared in inner scope with identical signature (name and type) as one in an outer scope, the compiler should allow this "syntactic sugar" and simply create a new variable that is actually referred to by some mashup in whatever intermediate code is used (MSIL, JIL, assembly). Then, remove the var declaration from count, and most standards about intra-method scope will make this work exactly the way you want. You may optionally require use of the "new" keyword on the inner variable declaration to confirm to the compiler that, yes, you really do want a variable with the same name that "hides" the outer scope definition. So, your snippet would only change as follows:

var x = "foo";
var count = 0;

loop (/* condition */) {

    var x = "bar"; //"hides" the outer x; maybe require "new" to confirm

    print (x); // "bar"

    count = count + 1; //works with the outer definition of count
}

print (x); // "foo"
print (count); // > 0
KeithS
Right, will go this way. Thank you! :)
wajda