LISP - String length
Lisp - Getting the Length of a Sequence
Section titled “Lisp - Getting the Length of a Sequence”In Common Lisp, length is a generic function used to find the number of elements in any sequence. Since strings are a type of sequence (specifically, a vector of characters), length is the standard function to determine a string’s length.
Basic Usage
Section titled “Basic Usage”The usage is straightforward: pass the sequence as an argument to the length function.
Example: Getting the length of a String
Section titled “Example: Getting the length of a String”Let’s define a string and use the length function to get the count of its characters.
;; Define a string using a local variable(let ((my-string "Modern Lisp is powerful!")) ;; Get its length (length my-string))Output
Section titled “Output”24A Common Point of Confusion: Quoting
Section titled “A Common Point of Confusion: Quoting”A common mistake for beginners is to quote a string literal, like (length '"my-string"). This is incorrect. The single quote (') is shorthand for the quote special operator, which prevents evaluation.
"my-string": This is a string literal. It evaluates to itself, a string object containing characters.'"my-string": This is a symbol. It evaluates to the symbol whose name ismy-string. A symbol is not a string, and trying to get its length will result in an error.
;; CORRECT: Get the length of a string(length "Hello") ; => 5
;; INCORRECT: Tries to get the length of the *symbol* named "Hello";; (length '"Hello") ; => This will signal a type error.Key Concepts: Unicode and Performance
Section titled “Key Concepts: Unicode and Performance”Unicode Characters
Section titled “Unicode Characters”Modern Lisp implementations are fully Unicode-aware. The length function correctly counts the number of characters, not the number of bytes. This is the behavior you almost always want.
;; The string contains 5 characters, including a Unicode emoji.(length "Hi 👋 Lisp")Output
Section titled “Output”9Performance: O(1) for Strings
Section titled “Performance: O(1) for Strings”It’s useful to know that length is a very fast operation for strings and vectors. Its time complexity is constant, or O(1), because the length is stored with the object itself.
In contrast, calling length on a list is a slower operation. The function must traverse the entire list to count its elements, making it a linear time, or O(n), operation.
;; Fast: O(1) operation(length "a very very long string...")
;; Slower: O(n) operation(length '(a very very long list ...))