Tuesday, June 3, 2003

Dynamic Scoping

Most sane individuals know that dynamic scoping is evil. However, it can be useful, and Dave Thomas shows that when made explicit it can actually be pretty nice. His code demonstrates some powerful Ruby features: using blocks to add syntax to the language and (ab)using callcc. Neither of these is possible in Python.

The way his first implementation works is that find_in_context throws an exception that’s caught in with_context. The exception stores a function that knows (a) the name being looked up, and (b) find_in_context’s continuation. with_context passes the function its context. If the context contains a binding for the name, the function calls the continuation with that value. This makes find_in_context return the value to its caller. The use of continuations is totally gratuitous, as Thomas later shows.

Food for thought: since exception handlers are themselves dynamically scoped, this implementation is, in a sense, circular.

1 Comment RSS · Twitter

Leave a Comment