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

From: John Clements (clements at brinckerhoff.org)
Date: Mon Jan 14 19:28:12 EST 2008

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



Posted on the users mailing list.