Prev Up Next

A lexical variable is visible throughout its scope, provided it isn't shadowed. Sometimes, it is helpful to temporarily set a lexical variable to a certain value. For this, we use the form fluid-let.2

(fluid-let ((counter 99))
  (display (bump-counter)) (newline)
  (display (bump-counter)) (newline)
  (display (bump-counter)) (newline))

This looks similar to a let, but instead of shadowing the global variable counter, it temporarily sets it to 99 before continuing with the fluid-let body. Thus the displays in the body produce

100
101
102

After the fluid-let expression has evaluated, the global counter reverts to the value it had before the fluid-let.

counter => 3

Note that fluid-let has an entirely different effect from let. fluid-let does not introduce new lexical variables like let does. It modifies the bindings of existing lexical variables, and the modification ceases as soon as the fluid-let does.

To drive home this point, consider the program

(let ((counter 99))
  (display (bump-counter)) (newline)
  (display (bump-counter)) (newline)
  (display (bump-counter)) (newline))

which substitutes let for fluid-let in the previous example. The output is now

4
5
6

Ie, the global counter, which is initially 3, is updated by each call to bump-counter. The new lexical variable counter, with its initialization of 99, has no impact on the calls to bump-counter, because although the calls to bump-counter are within the scope of this local counter, the body of bump-counter isn't. The latter continues to refer to the global counter, whose final value is 6.

counter => 6


2 fluid-let is a nonstandard special form. See sec 8.3 for a definition of fluid-let in Scheme.

Prev Up Next

Log in or register to write something here or to contact authors.