From: Kelly Murray
Subject: Re: declaring types with variable bits of precision
Date: 
Message-ID: <5u84r1$hul$1@sparky.franz.com>
In article <············@uic.edu>, "Bruce L. Lambert, Ph.D." <········@uic.edu> writes:
>> I want to write a fucntion that uses an array of unsigned-bytes, but I
>> want to let the user decide how many bits of precision to use in each
>> unsigned-byte. How do I write a declaration that allows me to do this?
>> 
>> For example:
>> (defparameter *num-bits* 8)
>> ...
>> (defun foo (an-array)
>>   (declare (type (simple-array (unsigned-byte *num-bits*) (*)) 
>>                  an-array))
>>   (dotimes (i (length an-array))
>>   
>>    ...))
>> 
>> The CLISP compiler chokes on this declaration. I could rewrite it as a
>> macro, and then it will work. But in my system, many functions need to
>> know how many bits are going to be in an unsigned-byte. Must I rewrite
>> all these functions as macros? There must be a better way.
>> 

If you are making the declarations for speed, then you can't really
change the type declaration at run time, after the code has been
compiled with a declaration for some specific type.  

What you can do to make the code more modular is use deftype to
define the array type, and then use that type name in the declarations.

(deftype my-byte-array ()
  `(simple-array (unsigned-byte ,*num-bits*) (*)))

(defun foo (an-array)
 (declare (type my-byte-array an-array))
 (aref an-array 0)
  ...)

Another more general way, (which is perhaps a bad hack)
that I've been known to do, 
is use read-time evaluation with #. to get complete control
over variable declarations.  Of course, the declaration macro
must be defined and loaded before compiling anything that uses it.
Common Lisp "outlawed" macros that expand into declarations,
so this #. useage is a CL-compliant way of achieving the same thing.
 
(defmacro my-declarations (var)

  ;; yes, this really is  a ` followed by a ' since this is run
  ;; at READ time, so it must return a form
   
  `'(declare (type (simple-array (unsigned-byte ,*num-bits*) (*)) ,var)
            (optimize (safety ,*my-safety*))))

(defun foo (an-array)
 #.(my-declarations an-array)
 (aref an-array 0)
  ...) 

            
-Kelly Murray  ···@franz.com