LISP 中的向量
在本文中,我们将讨论 LISP 中的向量。 LISP 中的向量是一维数组,也称为序列。我们可以使用向量函数和#符号创建一个向量
语法:
variable_name(vector element1 element2 ... element n)
or
variable_name #(element1 element2 ... element n)
示例:创建整数和字符向量并显示的 LISP 程序
Lisp
;create a vector with 5 integer elements
(setf data1 (vector 12 34 56 22 34))
;display
(write data1)
(terpri)
;create a vector with 5 integer elements using # symbol
(setf data1 #( 12 34 56 22 34))
;display
(write data1)
(terpri)
;create a vector with 5 character elements
(setf data2 (vector 'g 'e 'e 'k 's))
;display
(write data2)
(terpri)
;create a vector with 5 character elements
(setf data2 #( 'g 'e 'e 'k 's))
;display
(write data2)
Lisp
;create an empty array with size 10
(setq my_array (make-array 10 :fill-pointer 0))
;display array
(write my_array)
(terpri)
;push number 1 into array
(vector-push 1 my_array)
;push number 2 into array
(vector-push 2 my_array)
;push number 3 into array
(vector-push 3 my_array)
;push number 4 into array
(vector-push 4 my_array)
;display
(write my_array)
Lisp
;create an empty array with size 10
(setq my_array (make-array 10 :fill-pointer 0))
;display array
(write my_array)
(terpri)
;push number 1 into array
(vector-push 1 my_array)
;push number 2 into array
(vector-push 2 my_array)
;push number 3 into array
(vector-push 3 my_array)
;push number 4 into array
(vector-push 4 my_array)
;display
(write my_array)
;pop 1 item
(vector-pop my_array)
(terpri)
;display array
(write my_array)
;pop again 1 item
(vector-pop my_array)
(terpri)
;display array
(write my_array)
输出:
#(12 34 56 22 34)
#(12 34 56 22 34)
#(G E E K S)
#('G 'E 'E 'K 'S)
向量操作:
在给定的向量中,我们可以执行两个操作。他们是:
- 推送操作
- 弹出操作
1.推送操作:
这用于将元素插入到向量中
语法:
(vector-push element array_name)
在哪里
- array_name是一个输入数组
- element是要压入数组的元素
示例: LISP 程序创建一个大小为 10 的空数组并执行向量推送操作
语言
;create an empty array with size 10
(setq my_array (make-array 10 :fill-pointer 0))
;display array
(write my_array)
(terpri)
;push number 1 into array
(vector-push 1 my_array)
;push number 2 into array
(vector-push 2 my_array)
;push number 3 into array
(vector-push 3 my_array)
;push number 4 into array
(vector-push 4 my_array)
;display
(write my_array)
输出:
#()
#(1 2 3 4)
2.弹出操作:
此函数将一次删除最后插入的元素
语法:
(vector-pop array_name)
在哪里
- array_name是输入数组
示例:数组中的 POP 项目
语言
;create an empty array with size 10
(setq my_array (make-array 10 :fill-pointer 0))
;display array
(write my_array)
(terpri)
;push number 1 into array
(vector-push 1 my_array)
;push number 2 into array
(vector-push 2 my_array)
;push number 3 into array
(vector-push 3 my_array)
;push number 4 into array
(vector-push 4 my_array)
;display
(write my_array)
;pop 1 item
(vector-pop my_array)
(terpri)
;display array
(write my_array)
;pop again 1 item
(vector-pop my_array)
(terpri)
;display array
(write my_array)
输出:
#()
#(1 2 3 4)
#(1 2 3)
#(1 2)