1. Understand the Goal: The user wants a program that implements a persistent data structure.
-
Define "Persistent Data Structure":
- It's a data structure that always preserves the previous version of itself when it is modified.
- Such data structures are effectively immutable; modifications return a new structure that shares structure with the old one.
- Types of persistence:
- Partial: Can access old versions but not update them.
- Full: Can access and update old versions (branching).
- Confluent: Merging versions.
- For a code example, Partial Persistence is the standard interpretation (like how Git works or how data structures work in Clojure/Scala/Haskell).
-
Choose a Language:
- Python: Good for readability, but strict immutability isn't native (though possible via tuples/frozen sets/custom classes). Good for teaching the concept.
- Java/C#: Verbose.
- C++: Manual memory management makes structural sharing tricky for a simple example (smart pointers help, but increase complexity).
- Rust: Good, but ownership models might distract from the core algorithm.
- Go: Okay, but pass-by-value vs pointer can be confusing.
- Decision: Python is usually best for algorithmic clarity. I will use Python but design it using a functional/class-based approach that enforces immutability.
-
Choose a Data Structure to Implement:
-
Linked List: Too simple? Maybe a good starting point. (Cons cells).
-
Binary Search Tree (BST): A classic example. Easy to visualize structural sharing. If you change a leaf, you create new nodes up to the root, but share the untouched sibling subtrees.
-
Hash Array Mapped Trie (HAMT): The gold standard (used in Clojure/Scala), but too complex for a single file example.
-
Stack/Queue: Too similar to a list.
-
Decision: Persistent Binary Search Tree (BST) or a Persistent List. A BST demonstrates the concept of "Path Copying" very well.
-
Design the Persistent BST (Path Copying):
-
Concept: To change a node, we copy that node, make the change, copy its parent and point to the new node, copy the grandparent, etc., up to the root.
-
Sharing: Siblings of the path are not copied; they are referenced.
-
Class Structure: Node (value, left, right).
-
Operations: insert, search.
-
Crucial Detail: Methods should return a new root, leaving the original root untouched.
-
Drafting the Code (Mental or Scratchpad):
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(node, value):
if node is None:
return Node(value) # New node
if value < node.value:
# Return NEW node with new left child, old right child
return Node(node.value, insert(node.left, value), node.right)
else:
# Return NEW node with old left child, new right child
return Node(node.value, node.left, insert(node.right, value))
-
Refining the Example:
- I should show usage. Create
root1. Create root2 from root1 by inserting.
- Verify that
root1 hasn't changed.
- Verify that
root1 and root2 share memory for the unmodified parts (though in Python, checking memory sharing of primitives is hard, printing the traversal proves logical correctness).
-
Adding Complexity (Optional but good):
- Maybe a persistent list? It's simpler but less impressive than a tree.
- Let's stick to the BST because "Path Copying" is the core concept people look for.
-
Code Structure for the final response:
- Introduction: Explain what persistent data structures are (immutability + structural sharing).
- Technique: Explain "Path Copying".
- The Code: Python implementation of a Persistent BST.
- Usage/Demo: Show how Version 1 remains intact after creating Version 2.
- Memory Diagram (Text-based): Explain how the sharing works.
-
Self-Correction/Review:
- Python gotcha: Python passes references. If I do
node.left.value = 5, I break immutability. The class should ideally enforce immutability, but for a simple demo, just strictly creating new instances in methods is sufficient. I will name the class PersistentBST to be clear.
- Edge cases: Empty tree, duplicates (ignore or handle, let's handle by ignoring or inserting to right).
-
Writing the Explanatory Text:
- Key phrase: "Structural Sharing". This is what makes it efficient O(logn) space per update instead of O(n).
-
Final Code Polish: Add comments, type hinting (for clarity), and a print method to visualize the tree state.
(Self-Correction during drafting):
Maybe a Persistent Array/List is more intuitive?
A persistent array (like a rope or tree-based vector) is complex.
A persistent linked list is trivial (head stays, new cons node points to head).
The BST strikes the perfect balance of algorithmic interest and clarity.
Let's implement a BinarySearchTree where insert and delete return a new tree object, preserving the old one.
Plan:
- Define
TreeNode.
insert: Recursively copy nodes on the path. Return new root.
delete: Harder. Let's stick to insert and maybe remove if it's not too long. Actually, insert is enough to demonstrate the principle. Adding delete adds significant boilerplate (handling 2-child case). I will stick to insert to keep the code clean and focused on the persistence mechanism, or perhaps a very simple delete.
- Let's do
insert and print.
Wait, let's look at the user prompt again. "Create a program".
I should provide a complete, runnable script.
Let's refine the Python code.
class TreeNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
This is standard.
Let's think about the "Program".
It should output:
- State of Tree A.
- State of Tree B (derived from A).
- State of Tree A (unchanged).
- Show shared structure.
Let's proceed with generating the Python solution.
Here is a complete implementation of a Persistent Binary Search Tree in Python.
The Concept: Path Copying
To make a data structure persistent, we cannot simply modify nodes in place. Instead, we use a technique called Path Copying.
- Whenever a node needs to be changed (insertion or deletion), we create a new copy of that node with the updated data.
- Since the parent of that node now points to a "stale" child, we must also create a new copy of the parent.
- This bubbles up to the root.
- The result is a new root representing the new version, but it shares 99% of its structure with the old version (memory efficient).
The Implementation
import matplotlib.pyplot as plt
import networkx as nx
class TreeNode:
"""
An immutable node for a Persistent Binary Search Tree.
"""
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return f"Node({self.value})"
class PersistentBST:
"""
A Persistent Binary Search Tree.
Methods like 'insert' do not modify 'self'.
They return a NEW tree object representing the modified state.
"""
def __init__(self, root=None):
self.root = root
def insert(self, value):
"""
Returns a new PersistentBST containing the value.
The original tree remains unchanged.
"""
new_root = self._insert_recursive(self.root, value)
return PersistentBST(new_root)
def _insert_recursive(self, node, value):
# Base case: If slot is empty, return a new node.
# This creates the "copy" for this level.
if node is None:
return TreeNode(value)
if value < node.value:
# Recurse left. Create a NEW node copying current value,
# but with an updated left child.
return TreeNode(
node.value,
left=self._insert_recursive(node.left, value),
right=node.right # Right child is shared (pointer copied)
)
elif value > node.value:
# Recurse right. Create a NEW node copying current value,
# with updated right child.
return TreeNode(
node.value,
left=node.left, # Left child is shared
right=self._insert_recursive(node.right, value)
)
else:
# Value exists. In this implementation, we ignore duplicates.
# (Or we could return a new node with updated payload)
return node
def find(self, value):
"""Standard BST search (no persistence logic needed for reading)."""
return self._find_recursive(self.root, value)
def _find_recursive(self, node, value):
if node is None:
return False
if value == node.value:
return True
if value < node.value:
return self._find_recursive(node.left, value)
return self._find_recursive(node.right, value)
def to_list_inorder(self):
"""Helper to verify tree contents."""
res = []
self._inorder(self.root, res)
return res
def _inorder(self, node, res):
if node:
self._inorder(node.left, res)
res.append(node.value)
self._inorder(node.right, res)
# ==========================================
# Usage Demonstration
# ==========================================
def visualize_tree(tree, title, filename):
"""Optional: Visualizes the tree structure to show sharing."""
G = nx.DiGraph()
labels = {}
# We need to traverse the actual object structure to map it
# Note: This visualizes the nodes reachable from this specific root
nodes = [tree.root]
edges = []
while nodes:
n = nodes.pop()
if n:
labels[n.value] = n.value # simple label hack (assuming unique values)
G.add_node(id(n), value=n.value)
if n.left:
G.add_edge(id(n), id(n.left))
nodes.append(n.left)
if n.right:
G.add_edge(id(n), id(n.right))
nodes.append(n.right)
pos = nx.spring_layout(G)
plt.figure(figsize=(8, 5))
# Draw nodes with values
nx.draw(G, pos, with_labels=False, node_size=2000, node_color="skyblue")
node_labels = {id(n): n.value for n in [tree.root] if n} # crude label mapping for demo
# Proper label extraction needs traversal, simplified for brevity here.
# Just imagine the numbers inside circles!
plt.title(title)
plt.savefig(filename)
plt.close()
# 1. Create Initial Tree
print("Creating Version 1 (10, 5, 15)...")
v1 = PersistentBST()
v1 = v1.insert(10)
v1 = v1.insert(5)
v1 = v1.insert(15)
print(f"V1 Contents: {v1.to_list_inorder()}")
# 2. Create New Version based on V1
print("\nModifying V1 to create V2 (inserting 12)...")
# We do NOT overwrite v1. We capture the result in v2.
v2 = v1.insert(12)
print(f"V2 Contents: {v2.to_list_inorder()}")
# 3. Create another Version based on V1 (Branching)
print("\nModifying V1 to create V3 (inserting 3)...")
# We use V1 again as the base. This demonstrates forking history.
v3 = v1.insert(3)
print(f"V3 Contents: {v3.to_list_inorder()}")
# 4. Verify Persistence (Immutability)
print("\n--- Verification ---")
print(f"Is V1 unchanged? {v1.to_list_inorder() == [5, 10, 15]}")
print(f"Does V2 have '12'? {v2.find(12)}")
print(f"Does V1 have '12'? {v1.find(12)}")
print(f"Does V3 have '3'? {v3.find(3)}")
print(f"Does V1 have '3'? {v1.find(3)}")
print("\nStructure Sharing Explained:")
print("V2 and V3 share the nodes for '10' and '15'.")
print("Only the path from root to the new insertion (5->left or 10->right) was copied.")
How to interpret this code
- Immutability: Notice that
TreeNode never has its fields changed after creation. node.left never points to a different object once set.
- The
insert Logic:
- In a standard mutable BST,
node.left = new_node.
- In this persistent BST, we create a
new_node that looks exactly like the old node but has a different left child.
- Performance:
- Time Complexity: O(logn) (standard for BST).
- Space Complexity: O(logn) for the insertion operation (because we only copy the path from root to leaf). This is much better than copying the entire tree every time.
Real World Use Cases
- Version Control: Like Git.
v1 is a commit. v2 is the next commit. v3 is a bugfix branch created from v1.
- Undo/Redo: In a text editor, the state of the document is a tree. Pressing "Undo" simply points the cursor to the previous root of the tree.
- Databases: Datalog databases (like Datomic) use persistent B-Trees to query the database as it existed at a specific point in time without locking reads.