[racket] Box: When and why?

From: Greg Hendershott (greghendershott at gmail.com)
Date: Thu Oct 21 11:22:50 EDT 2010

Where can I find more information about the use scenarios for "box"?

The Guide is terse:

>>
3.11 Boxes

A box is like a single-element vector. It can print as a quoted #&
followed by the printed form of the boxed value. A #& form can also be
used as an expression, but since the resulting box is constant, it has
practically no use.
<<

This explains what a box is, but not why or when you would want to use one.

I see box used as in this example from servlet-dispatch.rkt:

(define (dispatch/servlet
...
  (define servlet-box (box #f))
...
  (filter:make
...
    (lambda (url)
      (or (unbox servlet-box)
          (let ([servlet
                 (parameterize ([current-custodian (make-custodian)]
                                [current-namespace
                                 (make-servlet-namespace
                                  #:additional-specs
                                  default-module-specs)])
                   (if stateless?
                       (make-stateless.servlet
servlet-current-directory stuffer manager start)
                       (make-v2.servlet servlet-current-directory
manager start)))])
            (set-box! servlet-box servlet)
            servlet))))))

And I'm scratching my head, not understanding the point of using a box
as opposed to a simple non-boxed value.

My question isn't about this code per se; only an example. Generally,
in what situations would you use a box, and why?

Thank you.


Posted on the users mailing list.