37 lines
1.4 KiB
Common Lisp
37 lines
1.4 KiB
Common Lisp
;;; CLOS 7: PRINT-OBJECT AND DEFAULT-INITARGS
|
|
;;;
|
|
;;; DEFSTRUCT (chapter 12) writes the constructor, the readers and
|
|
;;; the predicate for you. DEFCLASS spells them out by hand - and
|
|
;;; buys methods, inheritance, and defaults:
|
|
;;;
|
|
;;; :INITFORM fills one slot when nothing else does.
|
|
;;; :DEFAULT-INITARGS feeds an :INITARG its default, so
|
|
;;; MAKE-INSTANCE can still override it.
|
|
;;;
|
|
;;; PRINT-OBJECT is the method the printer calls: define it, and
|
|
;;; PRINC shows your objects your way. PRINT-UNREADABLE-OBJECT
|
|
;;; builds the #<...> frame around your text.
|
|
|
|
(defstruct candy filling size)
|
|
|
|
;; TODO: POINT starts at the origin unless you say otherwise.
|
|
(defclass point ()
|
|
((x :initarg :x :accessor point-x)
|
|
(y :initarg :y :accessor point-y)))
|
|
|
|
;; TODO: A point prints as #<POINT x=3 y=4>.
|
|
(defmethod print-object ((p point) stream)
|
|
(format stream "point"))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 'swirl (candy-filling (make-candy :filling 'swirl)))
|
|
(check-equal 0 (point-x (make-instance 'point)))
|
|
(check-equal 7 (point-x (make-instance 'point :x 7)))
|
|
(check-equal "#<POINT x=3 y=4>"
|
|
(with-output-to-string (s)
|
|
(princ (make-instance 'point :x 3 :y 4) s)))
|