Node:User-defined types, Next:, Previous:Methods, Up:Getting Started



2.0.3 User-defined types


(define-class <2D-vector> ()
  (x #:init-value 0 #:accessor x-component #:init-keyword #:x)
  (y #:init-value 0 #:accessor y-component #:init-keyword #:y))

(use-modules (ice-9 format))

(define-method (write (obj <2D-vector>) port)
  (display (format #f "<~S, ~S>" (x-component obj) (y-component obj))
           port))

(define v (make <2D-vector> #:x 3 #:y 4))

v --> <3, 4>

(define-method (+ (x <2D-vector>) (y <2D-vector>))
  (make <2D-vector>
        #:x (+ (x-component x) (x-component y))
        #:y (+ (y-component x) (y-component y))))

(+ v v) --> <6, 8>