Page 1 of 1

accessing children in CLOS?

Posted: Sun Dec 18, 2011 2:02 pm
by meekerdb
I want to read in some data from files and put the data into slots in members of a class. There are lots of sets of data. Then I want to be able to do things like plot and calculate statistics. But how do I access all the instances of the class that have been created as I read in the data? Can I MAP over the class some way, or do I have to GENSYM names for each instance and keep them in a list somewhere in order to access them?

Re: accessing children in CLOS?

Posted: Mon Dec 19, 2011 8:47 am
by ramarren
Instances of classes are first class, so they can be stored in collections in the same way as any other object. Why would you think you need to create names for instances? This seems to indicate confusion about fairly basic concepts of programming, and you might want to read a book starting from the basics such as Gentle Introduction to Symbolic Computation.

Re: accessing children in CLOS?

Posted: Mon Dec 19, 2011 3:53 pm
by Konfusius
CLOS doesn't manage a list of all instances automatically because this would be inefficient and unneccessary for most applications. But you can easily maintain such a list yourself with a global variable.

Code: Select all

(defclass my-class (...) (...))

(defvar *my-class-instances* nil)

(defmethod initialize-instance ((self my-class) ...)
  (call-next-method) ; initialize base classes
  (push self *my-class-instances*) ; add to instance list
  ; your own instance initialization here
  )