Guest User

Untitled

a guest
Apr 24th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. ; A macro for making Scheme 'objects' with private state and methods
  2. ; and a public API. Objects are generated as closures that take a
  3. ; symbol and a list of arguments, and call the named method with those
  4. ; arguments.
  5.  
  6. (define-syntax define-object (syntax-rules (var public private)
  7. ((_ "match?" symbol public (name . args) body ...)
  8. (eq? symbol 'name))
  9.  
  10. ((_ "match?" expression ...) #f)
  11.  
  12. ((_ "lookup" (name . args) body ...) name)
  13.  
  14. ((_ "lookup" name expression ...) name)
  15.  
  16. ((define-object name
  17. (modifier expression ...)
  18. ...)
  19. (define name (let ()
  20. (define expression ...)
  21. ...
  22. (lambda (symbol . args)
  23. (define proc (cond ((define-object "match?" symbol modifier expression ...)
  24. (define-object "lookup" expression ...))
  25. ...))
  26. (if (procedure? proc)
  27. (apply proc args)
  28. (error "No such method" symbol))))))))
  29.  
  30.  
  31. ; ----------------------------------------------------------------
  32. ; Example: a key-value store object. Only the 'set and 'get methods
  33. ; are exposed to the outside world.
  34. (define-object table
  35. (var table '())
  36.  
  37. (public (set name value)
  38. (let ((pair (find-or-create-pair-for name)))
  39. (set-cdr! pair value)))
  40.  
  41. (public (get name)
  42. (let ((pair (assq name table)))
  43. (if (pair? pair)
  44. (cdr pair)
  45. '())))
  46.  
  47. (private (find-or-create-pair-for name)
  48. (let ((pair (assq name table)))
  49. (if pair
  50. pair
  51. (let ((pair (cons name '())))
  52. (set! table (cons pair table))
  53. pair)))))
  54.  
  55.  
  56. (table 'get 'name) ; => '()
  57. (table 'get 'age) ; => '()
  58.  
  59. (table 'set 'name "James")
  60. (table 'set 'age 25)
  61.  
  62. (table 'get 'name) ; => "James"
  63. (table 'get 'age) ; => 25
  64.  
  65. (table 'table)
  66. ; [error] No such method :: table
  67.  
  68. (table 'find-or-create-pair-for)
  69. ; [error] No such method :: find-or-create-pair-for
Add Comment
Please, Sign In to add comment