Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function-local constant in Common Lisp?

I have a function like this:

(defun lookup-data (index-key)
   (let* ((key-table '("key0" "key1" "key2" ...))
          (index       (position index-key key-table :test #'string-equal))
          ...
   ; do stuff with index, among other things
 )

The key table (really just a list of strings, but it's being used as a lookup table to map a string to an index number) is a literal value known at read time. I was thinking perhaps it should be made a defparameter or defconstant, but it's not used anywhere outside this one function. I assume the fact that it's a literal means that most compilers can do constant-based optimization on it as-is, but is there something else I should do to mark it as a constant? What are the options here?

like image 692
Mark Reed Avatar asked Dec 13 '25 22:12

Mark Reed


1 Answers

Your code is fine. key-table is a constant, it will be created once, when the function is compiled.

PS. You can also use #. to create more complicated constants that require code:

(defun ... (...)
  (let ((unit #.(let ((u (make-array '(10000 10000) :element-type 'double-float
                                     :initial-element 0)))
                  (dolist (i 10000 unit)
                    (setf (aref u i i) 1))))
        ...)
    ...))

here the unit matrix unit is created at read time and is a constant (well, you can modify it, but...).

like image 189
sds Avatar answered Dec 16 '25 13:12

sds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!