declaring types for atributes in CLOS

Discussion of Common Lisp
Post Reply
lrodrig
Posts: 17
Joined: Thu Sep 16, 2010 4:52 pm

declaring types for atributes in CLOS

Post by lrodrig » Thu Mar 24, 2011 12:04 pm

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:

Code: Select all

(defclass foo ()
...
  (data :accessor data 
          :type 'single-float))
An I have a method:

Code: Select all

(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.

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: declaring types for atributes in CLOS

Post by ramarren » Thu Mar 24, 2011 3:14 pm

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.

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: declaring types for atributes in CLOS

Post by gugamilare » Thu Mar 24, 2011 4:11 pm

The problem is you might want to use the same accessor for another class, for instance:

Code: Select all

(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.

lrodrig
Posts: 17
Joined: Thu Sep 16, 2010 4:52 pm

Re: declaring types for atributes in CLOS

Post by lrodrig » Fri Mar 25, 2011 3:47 am

Hi,

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

Luis.

Post Reply