Mar*_*eed 3 lisp constants common-lisp local-variables
我有一个这样的函数:
(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
)
Run Code Online (Sandbox Code Playgroud)
键表(实际上只是一个字符串列表,但它被用作将字符串映射到索引号的查找表)是读取时已知的文字值。我想也许它应该被制作为defparameteror defconstant,但它没有在这个函数之外的任何地方使用。我认为它是一个字面量意味着大多数编译器可以按原样对其进行基于常量的优化,但是我还应该做些什么来将其标记为常量吗?这里有哪些选项?
你的代码没问题。
key-table是一个常量,它会在函数编译时创建一次。
附言。您还可以用来#.创建需要代码的更复杂的常量:
(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))))
...)
...))
Run Code Online (Sandbox Code Playgroud)
这里的单位矩阵unit是在读取时创建的,并且是一个常数(好吧,你可以修改它,但是......)。