[plt-scheme] caution about use of 'pair?' in programs with mutable pairs?

From: Marco Morazan (morazanm at gmail.com)
Date: Mon Jan 14 20:01:27 EST 2008

What are the semantics of mcar & mcdr? Since car & cdr are observers,
why do we need to differentiate them from mcar & mcdr? On the same
note, why does pair? return false on an mpair?

There is probably a perfectly simple answer to these questions, but I
really would like to hear the details.

Thanks in advance,


On Jan 14, 2008 7:28 PM, John Clements <clements at brinckerhoff.org> wrote:
> On Jan 14, 2008, at 4:13 PM, Matthias Felleisen wrote:
> >
> > On Jan 14, 2008, at 3:06 PM, John Clements wrote:
> >
> >> I feel lucky not to have been bitten by this, but I can see some
> >> potentially very painful bugs possible in a switchover from v3 code
> >> to v4 code; in particular, code that uses 'pair?' to distinguish
> >> empty from nonempty lists could misclassify mpairs as nulls,
> >> leading to some very unpleasant "non-fail-fast" errors.  Instead,
> >> it would seem to be wiser here to use (not (null? ...)) rather than
> >> (pair? ...)
> >
> > I don't understand your remark. When you know pair? of some value v,
> > you can use car/cdr. If you know (not (null? v)), what do you really
> > know?
> The scenario I'm imagining is this: I have an existing piece of code
> that is written using mutable pairs.  I upgrade to v4, and it stops
> working.  I get it working again by replacing instances of set-car!
> and set-cdr! with set-mcar! and set-mcdr!.  Along the way, I discover
> places where I need to construct lists using mlist and mcons rather
> than list and cons.  Now imagine that somewhere in there is this piece
> of code:
> (define (my-length l)
>   (cond [(pair? l) (+ 1 (my-length (mcdr l)))]
>         [else 0]))
> This will return zero on any mlist.  This is why I'm worried about
> uses of 'pair?'; because unlike mcar & mcdr, they don't immediately
> report an error when called with the wrong flavor of list.
> Again, this is all FWIW; perhaps no one will actually run into this
> bug, or perhaps this is a tiny instance in a much larger pool of
> similar possible scheme bugs.
> John
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.