本帖最后由 vectra 于 2015-12-2 20:58 编辑
LISP语言没有指针和引用,有时实在是不太方便,请看这个LISP可变长数组
- ;; 定义一个可以容纳len个数据的数组
- (defun array-def (len uid / ar i)
- (setq i 0)
- (repeat len
- (setq ar (cons (read (strcat uid (itoa i))) ar)
- i (1+ i)
- )
- )
- (list uid (reverse ar))
- )
- ;; 销毁数组对象并释放内存
- (defun array-clear (ar /)
- (foreach e (cadr ar)
- (set e nil)
- )
- )
- ;; 为数组指定索引位置赋值,成功返回值,失败返回nil
- (defun array-set (ar i val / uid)
- (setq uid (car ar))
- (if (and (>= i 0) (< i (length (cadr ar))))
- (set (read (strcat uid (itoa i))) val)
- )
- )
- ;; 获取数组指定索引位置值
- (defun array-get (ar i / uid)
- (setq uid (car ar))
- (if (and (>= i 0) (< i (length (cadr ar))))
- (vl-symbol-value (read (strcat uid (itoa i))))
- )
- )
- ;; 返回数组的容量
- (defun array-length (ar /)
- (length (cadr ar))
- )
- ;; 重新设置数组的容量
- (defun array-set-length (ar len / count uid i tmp)
- (setq uid (car ar)
- count (array-length ar)
- )
- (cond
- ((< len count)
- (setq ar (cadr ar))
- (repeat len
- (setq tmp (cons (car ar) tmp)
- ar (cdr ar)
- )
- )
- (foreach e ar
- (set e nil)
- )
- (list uid (reverse tmp))
- )
- ((> len count)
- (setq i 0)
- (repeat (- len count)
- (setq tmp (cons (read (strcat uid (itoa (+ count i)))) tmp)
- i (1+ i)
- )
- )
- (list uid (append (cadr ar) (reverse tmp)))
- )
- )
- )
- ;; 返回数组的LISP格式数据
- (defun array->list (ar /)
- (mapcar 'vl-symbol-value (cadr ar))
- )
演示:
_$ (setq ar (array-def 3 "U"))
("U" (U0 U1 U2))
_$ (array-length ar)
3
_$ (array->list ar)
(nil nil nil)
_$ (array-set ar 2 "222")
"222"
_$ (setq ar (array-set-length ar 10))
("U" (U0 U1 U2 U3 U4 U5 U6 U7 U8 U9))
_$ (array-length ar)
10
_$ (array->list ar)
(nil nil "222" nil nil nil nil nil nil nil)
_$ (array-set ar 10 "222") <- 下标是从0开始的,越界的下标造成赋值失败
nil
_$ (array-set ar 9 "222")
"222"
_$ (array-get ar 9)
"222"
_$ (array->list ar)
(nil nil "222" nil nil nil nil nil nil "222")
_1$ (array-clear ar)
nil
_1$ (array->list ar)
(nil nil nil nil nil nil nil nil nil nil)
看到length clear set get是不是找到点VB或者C的感觉来了呢。
大家也许都明白了,所谓的数组只不过是一组符号的管理器,符号是全局的,不要和已有的变量名称冲突呐。
当然,数组的访问实际上是直接对符号的访问,速度是相当快的,适合对性能有要求的随机访问,也没有了讨厌的subst cons操作了。
|