In principle, immutable == cannot be changed, and constant == immutable, with a common structure.
If I have a language in which arrays cannot be changed, the arrays are immutable. To “modify” an array, I have to create a new array and copy each element (except for one (s) that need to be changed) into a new array. This makes any update O (n), where n is the number of elements in the array. Obviously, this is ineffective for large n.
On the other hand, if I use a constant data structure instead of an array, instead of copying each item every time the data structure is “changed”, the new version has most of the same structure with the old.
Details are structure dependent, but wood is often used. If the tree is balanced, replacing the element means creating new copies of the nodes along the path from the root to the sheet containing the element. The remaining nodes are shared with the original version. The length of this path is O (n log (n)). Since the nodes are O (1) in size, the whole operation takes O (n log (n)) time and extra space.
Note that not all permanent structures effectively support the same operations. For example, in Clojure, lists are lists that are related to each other. You can effectively add and remove items to / from the front, but more on that. On the other hand, vectors allow you to efficiently receive any element and add / remove elements on the rear panel.
source share