Sunday, 15 March 2015

lisp - CLOS slot accessors: read but not write -



lisp - CLOS slot accessors: read but not write -

i have list of names of slots of clos object:

(defclass trial-data (standard-object) ((a-datum :accessor a-datum :initarg :a-datum :initform nil) (both-data :accessor both-data :initarg :both-data :initform 0) (cumulative-data :accessor cumulative-data :initarg :cumulative-data :initform nil) (name :accessor name :initarg :name :initform value))) (let* ((td (make-instance 'trial-data)) (slot-lst (mapcar #'slot-definition-name (class-slots (class-of td)))))

i can read values of these slots:

(let* ((td (make-instance 'trial-data)) (slot-lst (mapcar #'slot-definition-name (class-slots (class-of td))))) (funcall (symbol-function (nth 0 slot-lst)) td))

==> nil

but why can not write new values these slots? shouldn't class definition of trial-data have created accessor function each slot?

;; should set first slot, a-datum's, value 42 (let* ((td (make-instance 'trial-data)) (slot-lst (mapcar #'slot-definition-name (class-slots (class-of td))))) (setf (funcall (symbol-function (nth 0 slot-lst)) td) 42))

==>

;compiler warnings "/users/frank/documents/nrl/error/patrolbot/patrol construction notes & testing.lisp" : ; in anonymous lambda form @ position 123: undefined function (setf funcall) > error: undefined function (setf funcall) called arguments (42 #<standard-generic-function a-datum #x302001d1c5df> #<trial-data #x30200200d95d>) . > while executing: #<anonymous function #x30200200eb7f>, in process listener-2(5).

rainer joswigs's answer addresses issue of why can't set code have now. however, it's of import note there's no reason reader, writer, or accessor name has same slot name, if you've got slot name, should utilize (setf slot-value) it. e.g.,

(defclass foo () ((bar :accessor getbar :initform 42))) (defparameter *foo* (make-instance 'foo)) ;; neither of these work (setf (bar *foo*) 34) (funcall #'(setf bar) 34 *foo*) (slot-value *foo* 'bar) ;=> 42 (setf (slot-value *foo* 'bar) 36) ;=> 26 (slot-value *foo* 'bar) ;=> 36

lisp common-lisp accessor slot clos

No comments:

Post a Comment