レコード型の詳細を調べる


Tags: R6RS, レコード

(rnrs records inspection) の諸手続きを使うとレコード型について様々な情報を得ることができる。

(import (rnrs)
        (srfi :28))

(define (print-record record)
  (let ((rtd (record-rtd record)))
    (display
     (format "type: ~S~%\
              parent: ~S~%\
              uid: ~S~%\
              generative?: ~S~%\
              sealed?: ~S~%\
              opaque?: ~S~%\
              fields:~%"
             (record-type-name rtd)
             (cond ((record-type-parent rtd) => record-type-name)
                   (else #f))
             (record-type-uid rtd)
             (record-type-generative? rtd)
             (record-type-sealed? rtd)
             (record-type-opaque? rtd)))
    (let* ((fnv (record-type-field-names rtd))
           (l (vector-length fnv)))
      (do ((i 0 (+ i 1)))
          ((= i l))
        (display (format " #~S: ~S = ~S (~S)~%"
                         i (vector-ref fnv i)
                         ((record-accessor rtd i) record)
                         (if (record-field-mutable? rtd i) 'mutable 'immutable)))))))

(define-record-type point
  (fields
   (mutable x)
   (mutable y)))

(define-record-type colored-point
  (parent point)
  (sealed #t)
  (fields
   (immutable color)))

(define p (make-point 2 5))

(define cp (make-colored-point 3 4 'red))

(print-record p)
;; ->  type: point
;;     parent: #f
;;     uid: #f
;;     generative?: #t
;;     sealed?: #f
;;     opaque?: #f
;;     fields:
;;      #0: x = 2 (mutable)
;;      #1: y = 5 (mutable)
;;

(print-record cp)
;; -> type: colored-point
;;    parent: point
;;    uid: #f
;;    generative?: #t
;;    sealed?: #t
;;    opaque?: #f
;;    fields:
;;     #0: color = red (immutable)
;;