3
$\begingroup$

I was reading (wikipedia) about how the rope data structure might be suitable for a text editor. Within the article it mentions "If only nondestructive versions of operations are used, rope is a persistent data structure. For the text editing program example, this leads to an easy support for multiple undo levels." I don't understand how the undo works in this.

For example, let's say i had an existing rope with the left leaf as "hello" and the right leaf as "world". The parent (root) would have the value 5 (length of hello). Then, if i were to delete "world" i am just left with the root and left (hello) node. Now, if i wanted to "undo" the delete, haven't I already discarded the "world" node? Traditionally "undo" is done by placing things on a stack, but in this case I don't understand if using a stack what to put on it or how to do the undo in general.

$\endgroup$
4
$\begingroup$

The approach is to build a fully persistent version of the rope data structure. This then lets you keep a pointer to each version of the data structure: you have a pointer to version 1 ("hello world") and version 2 ("hello"). To undo the last operation, you just start working from version 1 rather than version 2. In particular, yes, you can store these pointers in a stack data structure. The point is that each modification creates what is effectively a new copy of the data structure, without modifying the old version. Of course, actually making an entire copy would be inefficient, so what the data structure does is share the parts of the tree that are unchanged.

For details on how to make a persistent version of the data structure, see What classes of data structures can be made persistent?. See also Array-like immutable (persistent) data structure implementation with fast indexing, append, prepend, iteration.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.