[racket] requiring a file in current-directory, if it exists

From: Matthew Butterick (mb at mbtype.com)
Date: Fri Oct 24 16:20:16 EDT 2014

I know that a hard-coded absolute path can be used in `require`:

(require (file "/path/to/directory/module.rkt"))))

But how can a generated path be used? Like so:

(require (file (path->string (build-path (current-directory) "module.rkt"))))

In particular, I want to `require` the file if it exists, or otherwise skip it.

I thought it should be a macro like this, but it doesn't work. The correct `require` syntax pops out, but it doesn't bind any identifiers. 

(define-syntax (try-current-directory-require stx)
  (syntax-case stx ()
    [(_ filename)
     (with-syntax ([path-string (datum->syntax stx (path->string (build-path (current-directory) (syntax->datum #'filename))))])
       (if (file-exists? (syntax->datum #'path-string))
           #'(require (prefix-in local: (file path-string)))

(try-current-directory-require "module.rkt")

Any suggestions? Is this a job for `define-require-syntax`?

Posted on the users mailing list.