views:

184

answers:

2
+3  Q: 

Slots in CLOS

Could any CL'er please explain 'slots' in CLOS? I am finding it difficult to understand the part after the slot name. That is in :

(defclass foo () (data1 :initarg foo))

What do the 'initarg' and other such similar things mean? I am re-reading manuals. So, I would really appreciate if any of you here could explain it to a layman like me.

Thanks!

+1  A: 

In a slot specification, the general syntax is (slot-name [slot-option option-value]...). The essentially-authoritatiev reference is the HyperSpec page on defclass, but in short:

:reader A function to read the value of the slot
:writer A function to write the value of the slot
:accessor A function to both read and (via SETF) set the value of the slot
:initarg A symbol to set the slot's value from MAKE-INSTANCE

There are more, but that list is the four I mostly use (actually, I mostly use :initarg and one of :accessor or :reader).

Vatine
+5  A: 

Your example is slightly wrong. It has to be:

(defclass foo ()
   ((data1 :initarg foo)))

Notice the added parentheses to indicate a list of slot descriptions.

DEFCLASS takes a list of slots. So with two slots we have:

(defclass foo ()
   ((data1 :initarg :data1arg
           :initform (random 1.0) 
           :type number
           :documentation "doc here"
           :accessor foo-data1-acc)
    (data2 :initarg :data2arg)))

DATA1 is the name of the slot. Behind that you find pairs of :keyword value.

:INITARG tells you what the parameter for MAKE-INSTANCE is. (make-instance 'foo :data1arg 10) ; creates the object and sets the slot data1 to 10. Usually you should use a keyword symbol (like :data1arg here).

:INITFORM sets the slot by default, when the object is created. Like in: (make-instance 'foo) ; creates the object. The slot is set to the value of the initform.

:TYPE specifies the type of the slot's object.

:DOCUMENTATION is just a string for, well, documentation.

:ACCESSOR specifies a function to read and write the slot.

(foo-data1-acc some-foo-object-here)             ; read
(setf (foo-data1-acc some-foo-object-here) 7)    ; write

Note that you can write the pairs in any order and that you can also specify multiple accessor functions. There are also :READER and :WRITER functions.

With CLOS you can specify all that within the DEFCLASS macro. These things are not automatically generated like in defstruct, which has a shorter notation.

The description of DEFCLASS is here: DEFCLASS. Short CLOS Intro.

Rainer Joswig
In the description of :INITFORM, should the slot data1 be set to 10 , or a random value from 0 too 1.0 ?
Amit
Yep, that was an error. Corrected above. When the initarg is not given, the initform is used to initialize the slot. I reality the mechanism is a bit more complicated, but often this is enough to know.
Rainer Joswig