
- LISP 教程
- LISP - 首頁
- LISP - 概述
- LISP - 環境
- LISP - 程式結構
- LISP - 基本語法
- LISP - 資料型別
- LISP - 宏
- LISP - 變數
- LISP - 常量
- LISP - 運算子
- LISP - 決策
- LISP - 迴圈
- LISP - 函式
- LISP - 謂詞
- LISP - 數字
- LISP - 字元
- LISP - 陣列
- LISP - 字串
- LISP - 序列
- LISP - 列表
- LISP - 符號
- LISP - 向量
- LISP - 集合
- LISP - 樹
- LISP - 雜湊表
- LISP - 輸入與輸出
- LISP - 檔案I/O
- LISP - 結構體
- LISP - 包
- LISP - 錯誤處理
- LISP - CLOS
- LISP 有用資源
- Lisp - 快速指南
- Lisp - 有用資源
- Lisp - 討論
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)
向量是序列,所有序列函式都適用於向量。請參閱序列章節,瞭解向量函式。
廣告