Dynamically avoiding duplicate identifiers in PLT Scheme

In this thread on the PLT discussion list, the original poster was encountering a problem while implementing a DSL where definitions were getting defined more than once in the code that he was generating. The problem is that the define function will not define the same name twice:

(define x 10)
(define x 12)
=> duplicate definition for identifier in: x

The solution would be to check if the given name is already bound before defining: if it was not defined, the define function should be used, otherwise the set! function should be used:

(define x 10)
(set! x 12)

Here is Andre’s solution from the thread:

(define-syntax define-if-not
  (λ (stx)
    (syntax-case stx ()
      [(_ var val)
       (with-syntax ([set!define (if (identifier-binding #'var 0)
                                      #'set!
                                      #'define)])
         (syntax
          (set!define var val)))])))

identifier-binding returns true unless the name is a top level binding or is not bound at all. If the name is already bound, use set!; otherwise use define.

Leave a Reply

Your email address will not be published. Required fields are marked *