In
MzScheme, you can
set! identifiers that you defined within your own module, but usually attempting to
set! identifiers that you imported from other modules will fail.
This is a good thing in general, since it allows module writers to reason locally about whether invariants for its identifiers are maintained. This leads to easier correctness arguments, and can also be a boon for improving execution speed for code (e.g., a compiler can detect if an identifier is never mutated, and generate better code).
However, sometimes you do want to be able to allow clients of your module to mutate state that you maintain. One way to do this is to provide "setter" procedures, which the client calls to mutate state. This is useful in some cases, but also can be a burden on the client (e.g. if they already have built up a large body of code that uses set! directly on identifiers in the top-level environment, and do not want to modify it to use a new protocol just because an identifier moved from the top-level to a module).
The following module defines a
provide-settable special form.
Any identifier provided with
provide-settable is then able to be used with set! in a client module.
(module setters mzscheme
(define-syntax provide-settable/defns
(syntax-rules ()
((_ ID ID-ALIAS FRESH-PROC!)
(begin
(define-syntax ID-ALIAS
(syntax-id-rules (set!)
((set! ID-ALIAS EXP)
(FRESH-PROC! EXP))
((ID-ALIAS . ARGS)
(ID . ARGS))
(_ ID)))
(define (FRESH-PROC! arg)
(set! ID arg))
(provide (rename ID-ALIAS ID))
))))
(define-syntax provide-settable
(lambda (stx)
(syntax-case stx ()
((_ ID)
(let* ((l (generate-temporaries #'(NAME NAME)))
(fresh-name (car l))
(fresh-set! (cadr l)))
#`(provide-settable/defns ID #,fresh-name #,fresh-set!)))
((_ ID REST ...)
#'(begin
(provide-settable ID)
(provide-settable REST)
...)))))
(provide provide-settable)
)
The solution relies on the support of
syntax-id-rules, which broadens macro invocations to identifier references and set! expressions (rather than just straightforward combinations). PLT Scheme added support for
syntax-id-rules circa version 205.8.
Now I can use this as follows:
(module A mzscheme
(require setters)
(define x 3)
(provide-settable x))
(module B mzscheme
(require A)
(define (foo)
(set! x 4))
(provide foo))
If we have only used
provide to export
x, then
MzScheme would complain the code in module
B, because it attempts to mutate
x. By using
provide-settable,
B can mutate
x and is unaware of the machinery under the hood (such as the call to the setter procedure).
(If someone knows how to write this macro without using
syntax-case, I'd like to hear about it.)
--
PnkFelix - 21 Jun 2005