This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

declaring types for atributes in CLOS

4 posts · 1083 views

Hi,

I'm trying to optimize a piece of CL code (in SBCL) by adding some type declarations. The thing is that I have a class:
(defclass foo ()
...
  (data :accessor data 
          :type 'single-float))
An I have a method:
(defmethod do-something((object foo) a)
  (declare (optimize (speed 3))
               (single-float a))
  ( / (data object) a))
I think that SBCL ignores "type" when defining atributes in classes and, indeed, the compiler complains about type uncertainty in the division first argument.

Does someone know if there is a way to declare the type of a slot or accessor (something similar to ftype) to optimize arithmetic operations in SBCL when dealing with CLOS objects?

Luis.

Re: declaring types for atributes in CLOS

Accessors are functions, and giving FTYPE for it seems to work. An alternative is to use the THE form to declare the return type of the form.

But I don't think it makes that much sense, since object access cost would drown any gain for simple cases, and for more complex cases it is better to extract the values in a LET form and declare types there.

Re: declaring types for atributes in CLOS

The problem is you might want to use the same accessor for another class, for instance:
(defclass foo ()
...
  (data :accessor data 
          :type 'single-float))

(defclass bar ()
...
  (data :accessor data 
          :type 'fixnum))
That is why it is a little difficult for SBCL to optimize these cases. You can either create a ftype declaration (like Ramarren said). If speed is really critical, I'd recommend to use structures, then you don't need to use ftype declarations for the accessors. Since structures are classes as well, it is possible to create methods on structures.

Re: declaring types for atributes in CLOS

Hi,

Thanks for your responses. I think that using structures will be a good solution here.

Luis.