Skip to content

Instantly share code, notes, and snippets.

@kurinoku
Last active June 18, 2023 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurinoku/1034f087b928ef9e0cfc3f0f5b4ad951 to your computer and use it in GitHub Desktop.
Save kurinoku/1034f087b928ef9e0cfc3f0f5b4ad951 to your computer and use it in GitHub Desktop.
Use identifier-binding to check if an identifier is defined or not
#lang racket
(require (for-syntax racket/syntax
syntax/parse))
(module+ test
(require rackunit)
(let ()
(define/if-not-exists t 0)
(check-equal? t 0))
(check-not-exn
(lambda ()
(define/if-not-exists t #t)
(define/if-not-exists t '())
(check-equal? t #t))))
(define-syntax (define/if-not-exists stx)
(syntax-parse stx
[(_ x:id value:expr)
#:when (not (identifier-binding #'x))
(syntax/loc stx (define x value))]
[(_ x:id value:expr)
(syntax/loc stx (void))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment