Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If strings are vectors, why are they immutable?

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?

like image 658
Golo Roden Avatar asked Dec 05 '22 21:12

Golo Roden


1 Answers

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.

like image 69
Rainer Joswig Avatar answered Feb 08 '23 02:02

Rainer Joswig