向量是一維數(shù)組,數(shù)組因此子類型。向量和列表統(tǒng)稱序列。因此,我們迄今為止所討論的所有序列的通用函數(shù)和數(shù)組函數(shù),工作在向量上。
向量函數(shù)使可以使用特定的值固定大小的向量。這需要任意數(shù)量的參數(shù),并返回包含這些參數(shù)的向量。
示例1
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setf v1 (vector 1 2 3 4 5)) (setf v2 #(a b c d e)) (setf v3 (vector 'p 'q 'r 's 't)) (write v1) (terpri) (write v2) (terpri) (write v3)
當執(zhí)行代碼,它返回以下結(jié)果:
#(1 2 3 4 5) #(A B C D E) #(P Q R S T)
請注意,LISP使用#(...)語法為向量的文字符號。可以使用此#(...)語法來創(chuàng)建并包含在代碼中的文字向量。
然而,這些是文字向量,所以修改它們沒有在LISP語言中定義。因此,對于編程,應(yīng)始終使用向量函數(shù),或者make-array函數(shù)來創(chuàng)建打算修改的向量。
make-array函數(shù)是比較通用的方式來創(chuàng)建一個矢量??梢栽L問使用aref函數(shù)的矢量元素。
示例 2
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setq a (make-array 5 :initial-element 0)) (setq b (make-array 5 :initial-element 2)) (dotimes (i 5) (setf (aref a i) i)) (write a) (terpri) (write b) (terpri)
當執(zhí)行代碼,它返回以下結(jié)果:
#(0 1 2 3 4) #(2 2 2 2 2)
make-array函數(shù)允許創(chuàng)建一個可調(diào)整大小的矢量。
函數(shù)fill-yiibaier參數(shù)跟蹤實際存儲在向量中的元素的數(shù)量。它的下一個位置,當添加元素的向量來填充的索引。
vector-push函數(shù)允許將元素添加到一個可調(diào)整大小的矢量的結(jié)束。它增加了填充指針加1。
vector-pop函數(shù)返回最近推條目,由1遞減填充指針。
示例
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setq a (make-array 5 :fill-yiibaier 0)) (write a) (vector-push 'a a) (vector-push 'b a) (vector-push 'c a) (terpri) (write a) (terpri) (vector-push 'd a) (vector-push 'e a) ;this will not be entered as the vector limit is 5 (vector-push 'f a) (write a) (terpri) (vector-pop a) (vector-pop a) (vector-pop a) (write a)
當執(zhí)行代碼,它返回以下結(jié)果:
#() #(A B C) #(A B C D E) #(A B)
向量是序列,所有序列函數(shù)是適用于向量。請參考序列章節(jié),對向量函數(shù)。