Lisp - Specialized Arrays



In Lisp, an array can hold any kind of object. A specialized array is way to restrict this functionality where only a specific type of element can be added. Following are key advantage of creating a specialized array.

  • Type Restriction− We can store specific type elements like integers, chars and single-float numbers which allows LISP to optimize storage of arrays of these primary types.

  • Increased Efficiency− LISP can use more efficient storage mechanism and avoid overhead of type checks during every element access.

  • Optimized Memory Allocation− Specialized arrays are generally for primitive types thus requiring less storage than general type arrays.

Commonly Specialized Array Types

We can use element-type construct with make-array function to define the required type of elements as shown below:

Array of Bits

We can create an array of bits to efficiently store boolean data.

; Create an array of bits
(make-array 10 :element-type 'bit)        

Array of Integers

We can create an array of integers to store numerical data.

; Create an array of integers
(make-array 10 :element-type 'integer)        

Array of Strings

We can create an array of strings to store character sequences.

; Create an array of strings
(make-array 10 :element-type 'character)        

Array of Single-Float

We can create an array of single precision floating point numbers for numerical computations.

; Create an array of single-float
(make-array 10 :element-type 'single-float)        

Advantages of Specialized Array

  • Type Safety− Due to element type restriction, type safety is ensured by LISP system automatically.

  • Increased Performance− Specialized array access/modification is significantly faster than general arrays.

  • Efficient Memory Usage− Lesser memory requirement as no storage requirement for type of each element.

Example

Following code check and predicates on different values.

main.lisp

; define an array of integers
(defvar my-integer-array (make-array 10 :element-type 'integer))

; assign integer values
(setf (aref my-integer-array 0) 10)
(setf (aref my-integer-array 1) 20)
(setf (aref my-integer-array 2) 30)

; Output: #(10 20 30 NIL NIL NIL NIL NIL NIL NIL)
(print my-integer-array)  

Output

When you execute the code, it returns the following result −

#(10 20 30 NIL NIL NIL NIL NIL NIL NIL) 
Advertisements