Lisp - 向量



向量是一維陣列,因此是陣列的子型別。向量和列表統稱為序列。因此,我們之前討論過的所有序列泛型函式和陣列函式都適用於向量。

建立向量

vector 函式允許您建立具有特定值的固定大小的向量。它接受任意數量的引數,並返回包含這些引數的向量。

示例

建立一個名為 main.lisp 的新原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; create and assign a vector to v1
(setf v1 (vector 1 2 3 4 5))
; create and assign a vector to v2
(setf v2 #(a b c d e))
; create and assign a vector to v3
(setf v3 (vector 'p 'q 'r 's 't))

; print v1
(write v1)
; terminate printing
(terpri)
; print v2
(write v2)
; terminate printing
(terpri)
; print v3
(write v3)

輸出

執行程式碼時,它返回以下結果:

#(1 2 3 4 5)
#(A B C D E)
#(P Q R S T)

請注意,LISP 使用 #(...) 語法作為向量的字面表示法。您可以使用此 #(... ) 語法來建立和包含程式碼中的字面向量。

但是,這些是字面向量,因此在 LISP 中未定義對其進行修改。因此,對於程式設計,您應該始終使用 **vector** 函式或更通用的函式 **make-array** 來建立您計劃修改的向量。

**make-array** 函式是建立向量的更通用的方法。您可以使用 **aref** 函式訪問向量元素。

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; create and assign an array of size 5 initilized with 0 values
(setq a (make-array 5 :initial-element 0))
; create and assign an array of size 5 initilized with 2 values
(setq b (make-array 5 :initial-element 2))

; loop for 5 times
(dotimes (i 5)
   ; set an array values
   (setf (aref a i) i))

; print a   
(write a)
;terminate printing
(terpri)
; print b
(write b)
; terminate printing
(terpri)

輸出

執行程式碼時,它返回以下結果:

#(0 1 2 3 4)
#(2 2 2 2 2)

填充指標

**make-array** 函式允許您建立可調整大小的向量。

該函式的 **fill-pointer** 引數跟蹤實際儲存在向量中的元素數量。當您向向量新增元素時,它是下一個要填充的位置的索引。

**vector-push** 函式允許您將元素新增到可調整大小向量的末尾。它將填充指標加 1。

**vector-pop** 函式返回最近推送的專案並將填充指標減 1。

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; create and assign an array of size 5 initilized with 0 values
(setq a (make-array 5 :fill-pointer 0))
; print a
(write a)
; add a to the vector a
(vector-push 'a a)
; add b to the vector a
(vector-push 'b a)
; add c to the vector a
(vector-push 'c a)
; terminate printing
(terpri)
; print vector a
(write a)
; terminate printing
(terpri)
; add d to the vector a
(vector-push 'd a)
; add e to the vector a
(vector-push 'e a)

;this will not be entered as the vector limit is 5
(vector-push 'f a)
; print vector a
(write a)
; terminate printing
(terpri)

; remove last pushed element
(vector-pop a)
; remove last pushed element
(vector-pop a)
; remove last pushed element
(vector-pop a)
; print vector
(write a)

輸出

執行程式碼時,它返回以下結果:

#()
#(A B C)
#(A B C D E)
#(A B)

向量是序列,所有序列函式都適用於向量。請參閱序列章節,瞭解向量函式。

廣告