user437528
user437528

Reputation:

Common Lisp: defstruct constructors and (declare (type blahblah blah))?

Let's say I have this:

(defstruct (derp
            (:constructor
             make-derp
             (&key (dimension 4))))
  (some-bits (make-array (list dimension dimension)
                         :element-type 'bit
                         :initial-element 0)))

I'd like to be able to (declare (type ...) blahblahblah) the 'dimension' parameter. Right now it accepts any value at all. Sure, make-array will error out on 0-or-less, but I also want to declare the type to be within a range, or whatever else I wish to use declare type for.

So anyway, I tried adding (declare (type (integer 1 32) dimension)) to various places in this defstruct, but it always yields a different error.

No luck on a casual Google search of these terms.

Can this be done somehow?

Upvotes: 1

Views: 891

Answers (1)

Rainer Joswig
Rainer Joswig

Reputation: 139261

Why would you want to declare it? Why not just check the type?

(defstruct (derp
            (:constructor
             make-derp (&key (dimension 4))))
  (some-bits (progn
               (check-type dimension (integer 0 10))
               (make-array (list dimension dimension)
                         :element-type 'bit
                         :initial-element 0))))

Generally above might not be robust enough. I'd then propose to write a MAKE-SOMETHING function, which does the checking upfront.

Note that you also can declare the type of the slot itself. Some CL will check that under some circumstances.

Upvotes: 3

Related Questions