Fine Grain Scoping in Scheme With Let
Posted by Rick on the 23rd of October, 2008 at 1:08 am under Programming. This post has Comments.In Java, there are four scopes: public, package friendly, protected and private. These are useful, but rather coarse. It would be nice to be able to specify a variable that was only visible to a select set of methods. For example, suppose you wanted to develop a counter that could not be modified without being accessed through methods that modified it. In Java, this would be accomplished with an inner class that had two methods. It’s interface would have to be declared publicly, though. In R5RS Scheme, this would look like:
(let ((z 0)) (list (lambda () (set! z (+ z 1))) (lambda () (set! z (- z 1)))))
This defines two functions that each close over the variable z such that you must call the first to increment z and you must call the second to decrement z. Because z is not defined at the top level, there is no way to access it and modify it directly — you must go through the functions. This allows the functions to be a bottleneck to the modification of z. So, if, for example, you wanted to log every time z was changed, you could add a logging command to each of the functions. This approach allows arbitrarily fine scoping to be defined. If you want a variable to be available to only one or two functions, it is trivial to do so using the “let” construct.
I’ll take a look at how you can accomplish similar results in JVM-based functional languages like Scala and Clojure in my next post.