3.26 Importing Modules Lazily: lazy-require
(lazy-require [module-path (fun-import ...)] ...)
fun-import = fun-id | (orig-fun-id fun-id)
If the enclosing relative phase level is not 0, then module-path is also placed in a submodule (with a use of define-runtime-module-path-index at phase level 0 within the submodule). Introduced submodules have the names lazy-require-auxn-m, where n is a phase-level number and m is a number.
When the use of a lazily-required function triggers module loading, it also triggers a use of register-external-module to declare an indirect compilation dependency (in case the function is used in the process of compiling a module).
> (lazy-require [racket/list (partition)]) > (partition even? '(1 2 3 4 5))
'(1 3 5)
> (module hello racket/base (provide hello) (printf "starting hello server\n") (define (hello) (printf "hello!\n")))
> (lazy-require ['hello ([hello greet])]) > (greet)
starting hello server
(lazy-require-syntax [module-path (macro-import ...)] ...)
macro-import = macro-id | (orig-macro-id macro-id)
Use lazy-require-syntax in the implementation of a library with large, complicated macros to avoid a dependence from clients of the library on the macro “compilers.” Note that only macros with exceptionally large compile-time components (such as Typed Racket, which includes a type checker and optimizer) benefit from lazy-require-syntax; typical macros do not.
(module runtime-support racket/base (define (ntimes-proc n thunk) (for ([i (in-range n)]) (thunk))) (provide ntimes-proc)) (module compiler racket/base (require 'runtime-support) (define-syntax-rule (ntimes n expr) (ntimes-proc n (lambda () expr))) (provide ntimes)) (module interface racket/base (require racket/lazy-require) (require 'runtime-support) (lazy-require-syntax ['compiler (ntimes)]) (provide ntimes))
> (module bad-no-runtime racket/base (define (ntimes-proc n thunk) (for ([i (in-range n)]) (thunk))) (define-syntax-rule (ntimes n expr) (ntimes-proc n (lambda () expr))) (provide ntimes))
> (module bad-client racket/base (require racket/lazy-require) (lazy-require-syntax ['bad-no-runtime (ntimes)]) (ntimes 3 (printf "hello?\n"))) > (require 'bad-client)
require: namespace mismatch;
reference to a module that is not instantiated