Sam Tobin-Hochstadt wrote at 09/28/2011 10:42 AM:
(require racket/mpair racket/splicing)


I guess the advantage of "let-splicing" here is that you can put the names by the definitions, rather than like the following more traditional way of doing this:

#lang racket/base

(require racket/mpair)

(define-values (variable-ref variable-set!)
  (let ((value-store (mlist (mcons 'variable #f))))
    (values (lambda (variable)
              (massoc variable value-store))
            (lambda (variable value)
              (set-mcdr! (variable-ref variable) value)))))

(variable-ref 'variable)

Incidentally, Marijn, given that that's a module right there, I suspect that the main reason you want to hide "value-store" like this is if this code was actually the result of a macro expansion. If not as the result of a macro expansion, then a perfectly normal practice is to use a top-level binding and simply not export it from the module, like:

#lang racket/base

(require racket/mpair)

(define value-store (mlist (mcons 'variable #f)))

(define (variable-ref variable)
  (massoc variable value-store))

(define (variable-set! variable value)
  (set-mcdr! (variable-ref variable) value))

(provide variable-ref variable-set!)

If you were writing a reusable library rather than experimenting, you'd probably not have a "value-store" binding that (presumably) will be mutated, but instead use a Racket parameter, so you'd have something like:

#lang racket/base

(require racket/mpair)

(define current-value-store (make-parameter (mlist (mcons 'variable #f))))

(define (variable-ref variable)
  (massoc variable (current-value-store)))

(define (variable-set! variable value)
  (set-mcdr! (variable-ref variable) value))

(provide variable-ref variable-set! current-value-store)

The parameter lets users of the library have multiple instances of the value store, rather than only one value store per program. You'd probably also provide a "make-value-store".

There's also a good chance you'd also use something other than mutable pairs, too, such as hashes or non-mutable pairs. You'll see examples in old Scheme textbooks of rolling your own records or objects using pairs, and that's good for learning, but for most real-world development, Racket has a large library of often better ways to accomplish things.

--
http://www.neilvandyke.org/

_________________________________________________
 For list-related administrative tasks:
 http://lists.racket-lang.org/listinfo/users

Reply via email to