Subject: Re: Avoiding unintentional variable capture
From: (Rob Warnock)
Date: 1999/09/27
Newsgroups: comp.lang.lisp
Message-ID: <7smo4l$>
Erik Naggum  <> wrote:
| * Ben Goetter
| | Of course a Lisp programmer always uses gensym where appropriate to write
| | a safe macro; thus also with Scheme, as any environment with defmacro
| | will also have gensym.  (If the Scheme lacks defmacro, how can it be
| | unsafe?  Unuseful, maybe, but unsafe?)
|   as I understand this, Scheme cannot generate symbols on the fly in code
|   in the first place, since the language is not defined in terms of sexprs...

But it can! The following is pure R4RS Scheme:

(define gensym
  (let ((count 0))
    (lambda rest  
      (define (normalize-arg x)
          ((null? x) "g")
          ((string? (car x)) (car x))
          ((symbol? (car x)) (symbol->string (car x)))
          (else (error "gensym: expects symbol/string/(), given: " (car x)))))
      (let ((prefix (normalize-arg rest)))
        (set! count (+ count 1))
          (string-append prefix (number->string count)))))))

> (gensym)
> (symbol? (gensym))
> (gensym)
> (gensym 'foo-)
> (gensym 'foo-)
> (gensym (string-append "foo-" (symbol->string (gensym 'bar-)) "-"))
> (gensym (string-append "foo-" (symbol->string (gensym 'bar-)) "-"))


Rob Warnock, 8L-846
Applied Networking
Silicon Graphics, Inc.		Phone: 650-933-1673
1600 Amphitheatre Pkwy.		FAX: 650-933-0511
Mountain View, CA  94043	PP-ASEL-IA