If strings are vectors, why are they immutable?

526 views Asked by At

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

2

There are 2 answers

1
Rainer Joswig On BEST ANSWER

Strings are not immutable in Common Lisp, they are mutable:

* is the last result from the Lisp listener

CL-USER 5 > (make-string 10 :initial-element #\-)
"----------"

CL-USER 6 > (setf (aref * 5) #\|)
#\|

CL-USER 7 > **
"-----|----"

CL-USER 8 > (concatenate 'string "aa" '(#\b #\b))
"aabb"

CL-USER 9 > (setf (aref * 2) #\|)
#\|

CL-USER 10 > **
"aa|b"

The only thing you should not do is modifying literal strings in your code. The consequences are undefined. That's the same issue with other literal data.

For example a file contains:

(defparameter *lisp-prompt* "> ")

(defparameter *logo-prompt* "> ")

If we compile the file with compile-file, then the compiler might detect that those strings are equal and allocate only one string. It might put them into read-only memory. There are other issues as well.

Summary

Strings are mutable.

Don't modify literal strings in your code.

0
KIM Taegyoon On

If you need mutability, don't use literal strings. Like so:

* (defparameter *s* (format nil "aaa"))
*S*

* (setf (elt *s* 1) #\b)
#\b

* *s*
"aba"