[plt-scheme] should `map' reuse cons cells?

From: Joe Marshall (jrm at ccs.neu.edu)
Date: Thu May 27 10:04:15 EDT 2004

Doug Orleans <dougo at place.org> writes:

> I'm not sure what the big sacrifice is:
>   (define (map f l)
>     (if (null? l)
> 	null
> 	(let ((h (car l)) (t (cdr l)))
> 	  (let ((fh (f h)) (ft (map f t)))
> 	    (if (and (eq? h fh) (eq? t ft))
> 		l
> 		(cons fh ft))))))

If you used `hash-consing' you'd get this behavior for free.

  (define *the-conses* (make-hash-table 'weak 'equal))

  (define *the-cell* (cons #f #f))

  (define (hcons car cdr)
    (set-car! *the-cell* car)
    (set-cdr! *the-cell* cdr)
    (hash-table-get *the-conses* *the-cell*
                    (lambda ()
                      (begin0 *the-cell*
                        (hash-table-put! *the-conses* *the-cell* *the-cell*)
                        (set! *the-cell* (cons #f #f))))))

  (define (hmap f l)
    (if (null? l)
        (hcons (f (car l)) (hmap f (cdr l)))))

Posted on the users mailing list.