From: Bjorn Solberg
Subject: How to call a dynamic writer method for a slot?
Date:
Message-ID: <m33ag1ccfe.fsf@famsolberg.com>
Say I have the following class:
(defclass tst ()
((a1
:initarg :a1
:accessor a1)
(a2
:initarg :a2
:accessor a2)
))
However, for the a2 slot, I need some transformation to happen for the
read and write:
(defmethod a2 ((obj tst))
(* 2 (slot-value obj 'a2)))
(defmethod (setf a2) (value (obj tst))
(setf (slot-value obj 'a2) (/ value 2)))
(defparameter *a* (make-instance 'tst :a1 20 :a2 40))
(defparameter *f* 'a2)
*f* now holds the name of the method I want to call, so I can do
(funcall (symbol-function *f*) *a*)
to call the a2 read method on my *a* object. How can I use *f* to set
the new value using the (setf a2) method?
If *f* was a string, I would just intern it first to get to the symbol,
but I'd still have the same problem with getting to the setf method.
The background here is a need to call each of a dynamic list of methods
on an object, with the list of methods coming in as an array of strings
or symbols representing the method names.
Thanks,
Bjorn.
In article <··············@famsolberg.com>,
Bjorn Solberg <··········@hekneby.org> wrote:
> Say I have the following class:
>
> (defclass tst ()
> ((a1
> :initarg :a1
> :accessor a1)
> (a2
> :initarg :a2
> :accessor a2)
> ))
>
> However, for the a2 slot, I need some transformation to happen for the
> read and write:
>
> (defmethod a2 ((obj tst))
> (* 2 (slot-value obj 'a2)))
>
> (defmethod (setf a2) (value (obj tst))
> (setf (slot-value obj 'a2) (/ value 2)))
>
>
> (defparameter *a* (make-instance 'tst :a1 20 :a2 40))
>
> (defparameter *f* 'a2)
>
> *f* now holds the name of the method I want to call, so I can do
>
> (funcall (symbol-function *f*) *a*)
>
> to call the a2 read method on my *a* object. How can I use *f* to set
> the new value using the (setf a2) method?
(funcall (fdefinition `(setf ,*f*)) new-value *a*)
--
Barry Margolin, ······@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
From: Bjorn Solberg
Subject: Re: How to call a dynamic writer method for a slot?
Date:
Message-ID: <m3zli5sj0p.fsf@famsolberg.com>
Barry Margolin writes:
> In article <··············@famsolberg.com>,
> Bjorn Solberg <··········@hekneby.org> wrote:
[...]
>> *f* now holds the name of the method I want to call, so I can do
>>
>> (funcall (symbol-function *f*) *a*)
>>
>> to call the a2 read method on my *a* object. How can I use *f* to set
>> the new value using the (setf a2) method?
> (funcall (fdefinition `(setf ,*f*)) new-value *a*)
Awesome, I didn't know of fdefinition. It seems to do what
symbol-function does, but more. It works like a charm.
Thanks,
Bjorn.