Saturday, 15 January 2011

lisp - Why can CLOS slots be unbound? -



lisp - Why can CLOS slots be unbound? -

it said, special variables in mutual lisp can unbound. lexical variables default value nil. thought class slots exist in closure, don't.

if define clos slots without :initform parameter (in hope bound nil anyway) , not supply values when creating instance, i'll instance unbound slots. why so? it's not handy.

clos instances not closures

clos instances not implemented closures. difficult. info construction vector slots. similar mutual lisp's structures. difference between clos instances , structures complicates it: possible clos instances alter number of slots @ runtime , 1 can alter class of clos instance @ runtime.

making sure slots have nil value

with advanced clos can create sure slots have nil value. note functions in bundle clos in illustration may in bundle in cl.

this functions looks on slots of instance. if slot unbound, gets set nil.

(defun set-all-unbound-slots (instance &optional (value nil)) (let ((class (class-of instance))) (clos:finalize-inheritance class) (loop slot in (clos:class-slots class) name = (clos:slot-definition-name slot) unless (slot-boundp instance name) (setf (slot-value instance name) value)) instance))

we create mixin class:

(defclass set-unbound-slots-mixin () ())

the prepare run after initializing object.

(defmethod initialize-instance :after ((i set-unbound-slots-mixin) &rest initargs) (set-all-unbound-slots nil))

example:

(defclass c1 (set-unbound-slots-mixin) ((a :initform 'something) b c)) cl-user 1 > (describe (make-instance 'c1)) #<c1 4020092aeb> c1 b nil c nil

lisp common-lisp slot clos

No comments:

Post a Comment