Self Reference in CLOS
Posted: Sat Jun 14, 2014 2:44 pm
I haven't seen an example of a class which can reference itself, so is it wise/safe to do this? :
I couldn't get the (setf this) to play nice without the self slot having both a reader and writer. Any help or advice would be appreciated. Thanks.
Code: Select all
(defclass self−reference()
((name :accessor acc−name
:initarg name
:initform ’())
(func :accessor acc−func
:initarg func
:initform ’())
(self :accessor this ;; should this be a reader?
:initarg self
:initform ’())))
(defmethod initialize−instance :before ((sr self−reference) &key)
(setf (acc−name sr) ’default)
(setf (acc−func sr) #’(lambda(x)x)) ;; just a placeholder
(setf (this sr) sr)) ;; store a reference to the current class instance <self>
(setf sr0 (make−instance ’self−reference))
(format t "instance : ~S name: ~S this: ~S " sr0 (acc−name sr0) (this sr0))
==> instance : #<SELF−REFERENCE {2420AC19}> name: DEFAULT this: #<SELF−REFERENCE {2420AC19}>