Previous: , Up: structs   [Contents][Index]


5.2 Example of structure handling API

The code below shows how we could define a public API to handle structures:

(define-syntax-rule (make-<colour> ?red ?green ?blue)
  (##sys#make-structure '<colour> ?red ?green ?blue))

(define-syntax-rule (colour? ?obj)
  (##sys#structure? ?obj '<colour>))

(define-syntax-rule (check-colour ?obj ?loc)
  (##core#check
   (##sys#check-structure ?obj '<colour> (quote ?loc))))

(define-syntax-rule (colour-red ?stru)
  (check-colour ?stru 'colour-red)
  (##sys#slot ?stru 1))

(define-syntax-rule (colour-green ?stru)
  (check-colour ?stru 'colour-green)
  (##sys#slot ?stru 2))

(define-syntax-rule (colour-blue ?stru)
  (check-colour ?stru 'colour-blue)
  (##sys#slot ?stru 3))

(define-syntax-rule (colour-red-set! ?stru ?new-red-value)
  (check-colour ?stru 'colour-red)
  (##sys#setslot ?stru 1 ?new-red-value))

(define-syntax-rule (colour-green-set! ?stru ?new-green-value)
  (check-colour ?stru 'colour-green)
  (##sys#setslot ?stru 2 ?new-green-value))

(define-syntax-rule (colour-blue-set! ?stru ?new-blue-value)
  (check-colour ?stru 'colour-blue)
  (##sys#setslot ?stru 3 ?new-blue-value))

here are some usage examples:

(let ((col (make-<colour> 0.2 0.3 0.4)))
  (check-colour col 'here)
  (##sys#slot col 0))
⇒ <colour>

(colour? (make-<colour> 0.2 0.3 0.4)))  ⇒ #t
(colour? "ciao"))                       ⇒ #f

(let ((col (make-<colour> 0.2 0.3 0.4)))
  (values (colour-red   col)
          (colour-green col)
          (colour-blue  col)))
⇒ 0.2 0.3 0.4

(let ((col (make-<colour> 0.2 0.3 0.4)))
  (colour-red-set!   col 0.5)
  (colour-green-set! col 0.6)
  (colour-blue-set!  col 0.7)
  (values (colour-red   col)
          (colour-green col)
          (colour-blue  col)))
⇒ 0.5 0.6 0.7

Previous: , Up: structs   [Contents][Index]