[plt-scheme] boxes?

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Tue Jan 23 20:42:56 EST 2007

On 1/23/07, gregory.woodhouse at sbcglobal.net
<gregory.woodhouse at sbcglobal.net> wrote:
> The genesis of my original question was a combination of a misreading of a manual, and the observation that numbers and pairs just don't behave the same way:
> > (define (test1 x)
>     (set! x 4))
> > (define x 1)
> > (test1 x)
> > x
> 1
> > (define (test2 x)
>     (set-car! x 4))
> > (define x '(1 1))
> > (test2 x)
> > x
> (4 1)

The problem here is not that numbers and lists work differently, but
that lists and *variables* work differently.  The (set! ...) form
works on variables, not values; the set-car! form works on values.  It
would be possible to implement integers that had a "set-integer!"
procedure, so you could modify an integer as it was passed around, but
that's not the same as set!.

Boxes, like variables, contain a mutable reference to a single value,
but unlike variables they are values that can be passed around, not
names bound in a lexical scope.  So the function test1 above could be
written as:

> (define (test1-boxed b)
    (set-box! b 4))
> (define v (box 1))
> (test1-boxed v)
> (unbox v)

Some languages, like SML, clear up the variable/value distinction by
allowing mutable values (boxes, records or vectors with mutable
fields, etc.) but disallowing mutable variables.  Without set!,
perhaps the value-mutation procedures aren't as confusing.

Carl Eastlund

Posted on the users mailing list.