Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing slots based on other slot values in Common Lisp Object System class definitions

In my class definition, I want to initialize one slot based on the value of another slot. Here is the sort of thing I would like to do:

(defclass my-class ()
  ((slot-1 :accessor my-class-slot-1 :initarg slot-1)
   (slot-2 :accessor my-class-slot-2 :initform (list slot-1))))

However this doesn't compile:

1 compiler notes:

Unknown location:
  warning: 
    This variable is undefined:
      SLOT-1

  warning: 
    undefined variable: SLOT-1
    ==>
      (CONS UC-2::SLOT-1 NIL)


Compilation failed.

Is there a way to do this?

like image 506
Paul Reiners Avatar asked Sep 01 '10 16:09

Paul Reiners


3 Answers

Use initialize-instance :after documented here

like image 143
Doug Currie Avatar answered Sep 29 '22 11:09

Doug Currie


Here is Doug Currie's answer expanded:

(defclass my-class ()
  ((slot-1 :accessor my-class-slot-1 :initarg :slot-1)
   (slot-2 :accessor my-class-slot-2)))

(defmethod initialize-instance :after 
           ((c my-class) &rest args)
  (setf (my-class-slot-2 c) 
        (list (my-class-slot-1 c))))

Here's a call showing that it works:

> (my-class-slot-2 (make-instance 'my-class :slot-1 "Bob"))
("Bob")

See this article for more details.

like image 43
Paul Reiners Avatar answered Sep 29 '22 11:09

Paul Reiners


(defparameter *self-ref* nil)


(defclass self-ref ()
  ()

  (:documentation "
Note that *SELF-REF* is not visible to code in :DEFAULT-INITARGS."))


(defmethod initialize-instance :around ((self-ref self-ref) &key)
  (let ((*self-ref* self-ref))
    (when (next-method-p)
      (call-next-method))))



(defclass my-class (self-ref)
  ((slot-1 :accessor slot-1-of :initarg :slot-1)
   (slot-2 :accessor slot-2-of
           :initform (slot-1-of *self-ref*))))




CL-USER> (let ((it (make-instance 'my-class :slot-1 42)))
           (values (slot-1-of it)
                   (slot-2-of it)))
42
42
CL-USER> 
like image 35
lnostdal Avatar answered Sep 29 '22 09:09

lnostdal