Self Reference in CLOS

Discussion of Common Lisp
Post Reply
macrolyte
Posts: 40
Joined: Sat Jan 25, 2014 8:56 pm
Location: The wilderness of North America

Self Reference in CLOS

Post by macrolyte » 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? :

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}>

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.

pjstirling
Posts: 166
Joined: Sun Nov 28, 2010 4:21 pm

Re: Self Reference in CLOS

Post by pjstirling » Sat Jun 14, 2014 3:01 pm

Since CLOS methods require that the instance is passed to the method, I don't really understand why you would want this?

macrolyte
Posts: 40
Joined: Sat Jan 25, 2014 8:56 pm
Location: The wilderness of North America

Re: Self Reference in CLOS

Post by macrolyte » Sat Jun 14, 2014 3:35 pm

pjstirling wrote:Since CLOS methods require that the instance is passed to the method, I don't really understand why you would want this?
I was toying with some ideas on constructors, and ways to distinguish between multiple running instances, for now. It seems safe, I just want to be sure. Thanks again.

Post Reply