Open In App

Vectors in LISP

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss Vectors in LISP. Vectors in LISP are one-dimensional arrays which are also known as sequences. We can create a vector using vector function and # symbol

Syntax:

variable_name(vector element1 element2 ... element n)
or
variable_name #(element1 element2 ... element n)

Example: LISP Program to create integer and character vectors and display

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)


Output:

#(12 34 56 22 34)
#(12 34 56 22 34)
#(G E E K S)
#('G 'E 'E 'K 'S)

Vector operations:

In the given vector we can perform two operations. They are:

  • push operation
  • pop operation

1. Push Operation:

This is used to insert an element into a vector

Syntax:

(vector-push element array_name)

where

  1. array_name is an input array
  2. element is an element to be pushed in an array

Example: LISP Program to create an empty array with size 10 and perform the vector push operation

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)


Output:

#()
#(1 2 3 4)

2. Pop Operation:

This function will remove the last inserted element at a time

Syntax:

(vector-pop array_name)

where

  1. array_name is the input array

Example: POP items in an 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)


Output:

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


Last Updated : 26 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads