Last update October 21, 2004

DWiki /
Dynamic Closures



Difference (last change) (Author, normal page display)

Changed: 49c49
(From DWiki)
(From DWiki)

A form of closure which employs dynamic scope. Closures are a powerful technique in which callbacks can retain implicit scope during the "call back", for example.

No more littering your code with extra context parameters and casting...

For example:

void apply_all (int table[], delegate (int) dg) {

  for (int i = 0; i < table.length; ++i) {
    dg(table[i]);
  }
}

void test () {

  int mytable[] = [1, 2, 3];
  int offset = 4;
  void func (int val) {
    printf("%u,",val+offset);
  }
  apply_all(mytable,func);
}

This feature is not without its pitfalls. In the above example, "offset" is in both the dynamic and lexical scope of "func", so it works. If, however, the code were structured such that "offset" fell out of dynamic scope during execution for some reason, the technique will fail.

For example, consider this modification:

delegate (int) create_func () {

  int offset = 4;
  return delegate (int val) {
    printf("%u,",val+offset);
  }
}

void test () {

  int mytable[] = [1, 2, 3];
  apply_all(mytable,create_func());
}

Now "offset" is no longer in dynamic scope, so its value is not defined. The stack location of "offset" will likely be overwritten by "apply_all's" local variable "i".

For a highly relevant (and recommended) discussion of dynamic versus lexical scope from the Lisp/Scheme world, see DynamicScoping on the c2 wiki.

Walter has indicated that he has a plan for a runtime check to catch this type of error.


(From DWiki)


FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: October 21, 2004 12:15 (diff))