Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ; A macro for making Scheme 'objects' with private state and methods
- ; and a public API. Objects are generated as closures that take a
- ; symbol and a list of arguments, and call the named method with those
- ; arguments.
- (define-syntax define-object (syntax-rules (var public private)
- ((_ "match?" symbol public (name . args) body ...)
- (eq? symbol 'name))
- ((_ "match?" expression ...) #f)
- ((_ "lookup" (name . args) body ...) name)
- ((_ "lookup" name expression ...) name)
- ((define-object name
- (modifier expression ...)
- ...)
- (define name (let ()
- (define expression ...)
- ...
- (lambda (symbol . args)
- (define proc (cond ((define-object "match?" symbol modifier expression ...)
- (define-object "lookup" expression ...))
- ...))
- (if (procedure? proc)
- (apply proc args)
- (error "No such method" symbol))))))))
- ; ----------------------------------------------------------------
- ; Example: a key-value store object. Only the 'set and 'get methods
- ; are exposed to the outside world.
- (define-object table
- (var table '())
- (public (set name value)
- (let ((pair (find-or-create-pair-for name)))
- (set-cdr! pair value)))
- (public (get name)
- (let ((pair (assq name table)))
- (if (pair? pair)
- (cdr pair)
- '())))
- (private (find-or-create-pair-for name)
- (let ((pair (assq name table)))
- (if pair
- pair
- (let ((pair (cons name '())))
- (set! table (cons pair table))
- pair)))))
- (table 'get 'name) ; => '()
- (table 'get 'age) ; => '()
- (table 'set 'name "James")
- (table 'set 'age 25)
- (table 'get 'name) ; => "James"
- (table 'get 'age) ; => 25
- (table 'table)
- ; [error] No such method :: table
- (table 'find-or-create-pair-for)
- ; [error] No such method :: find-or-create-pair-for
Add Comment
Please, Sign In to add comment