Lisp - Sequence length



Lisp provides length function to get the size of a sequence. length function works on most type of the sequences like list, vector, strings etc.

Syntax

(length sequence)

Argument

sequence − is the sequence whose length is to be determined. It can be a list, vector or string.

Returns

A non-negative integer representing the size of the sequence.

Example

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; prints length of the string; 3
(write(length "abc"))       
(terpri)

; prints length of the list; 4
(write(length '(a b c d)))
(terpri)

; prints length of a vector; 5   
(write(length #(1 2 3 4 5))) 
(terpri)

; print 0 as length of empty list
(write(length nil))        

Output

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

3
4
5
0

length of Adjustable Array

In case of Adjustable arrays, length function returns the total number of active elements instead of size of the array. Active length of an adjustable array is driven by fill pointer as shown in example below:

main.lisp

; define an array of size 10
(defvar my-array (make-array 10 :adjustable t :fill-pointer t :initial-element 0))

; print the length of array
(write(length my-array))
(terpri)

; decrease size to 5 (logical size)
(setf my-array (adjust-array my-array 5 :fill-pointer t)) 
; print updated length of the array
(write(length my-array))

Output

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

10
5
Advertisements