The user wants a program that implements a persistent data structure.
1. Understand the Request:
- Target: A persistent data structure.
- Language: Not specified. Python, Java, C++, or Haskell are common choices. Python is generally accessible, but Java or C# are better for showing the structure clearly (objects/references). I'll choose Python for readability, but I need to be careful with mutability.
- Key Concept: "Persistent" in computer science doesn't mean "saved to disk." It means that modifications create a new version of the data structure while preserving the previous version. This is often called "immutability" or "copy-on-write" semantics at the structural level.
2. Choose a Data Structure to Implement:
- Arrays/Lists: Hard to make efficiently persistent (path copying is O(n)). Not the best demo.
- Linked Lists: Very easy (prepend is O(1)). A classic example.
- Binary Trees (BST/AVL/Red-Black): Good for O(logn) operations. Path copying is efficient.
- Hash Array Mapped Tries (HAMT): This is how Clojure/Scala/Java's persistent maps work. A bit complex for a single-file demo.
Decision: I'll implement a Persistent Binary Search Tree using structural sharing (path copying). It's complex enough to show the concept clearly but not so complex that the code is unreadable. I will also include a simple persistent list example for contrast.
3. Design the Persistent Binary Search Tree:
- Node Class:
value: The data.
left: Left child.
right: Right child.
- Crucial: These fields should be immutable (or treated as such).
- Operations:
insert(value): Returns a new root. The old root remains unchanged.
search(value): Standard BST search (doesn't change structure).
delete(value): (Optional, but makes it complete). Let's stick to insert to keep the code concise and focused on the persistence aspect, or maybe implement a simple delete. Let's stick to Insert and a visualizer.
- Mechanism (Path Copying):
- When inserting into the left subtree, we return a new node where the
left pointer points to the result of the recursive insert. The right pointer shares the reference to the old right subtree. This is "structural sharing."
4. Drafting the Code (Mental or Scratchpad):
Python implementation:
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)
if value < node.value:
# Create new node, keep old right, update left
return Node(node.value, insert(node.left, value), node.right)
else:
# Create new node, keep old left, update right
return Node(node.value, node.left, insert(node.right, value))
5. Refining the Example:
- Just the class isn't enough. I need a driver to demonstrate persistence.
- I should create version 1, then version 2 from version 1, then version 3 from version 2.
- Then, verify that version 1 is still intact.
6. Adding a "Persistent List" (Stack) example:
- It's simpler and helps reinforce the concept.
push(item) -> returns new head.
pop() -> returns (new_head, item).
7. Structuring the Final Output:
- Explanation: Briefly define what persistent data structures are (immutability + structural sharing).
- Implementation: Python code.
- Define the
PersistentTree class.
- Define the
Node class.
- Demonstration: A
main block that creates versions and checks if old versions are modified.
8. Refining the Code (Self-Correction):
- Issue: Just doing
insert might result in an unbalanced tree if I insert sorted data.
- Fix: I'll insert random data or explicitly non-sorted data in the example to keep the tree decent.
- Enhancement: Add a
print_tree method to visualize the structure.
9. Final Code Structure (Python):
import copy # Not needed if doing structural sharing
class TreeNode:
...
class PersistentBST:
# Wrapper to manage the root easily
def __init__(self, root=None):
self.root = root
def insert(self, value):
# Returns a new PersistentBST object
new_root = self._insert_recursive(self.root, value)
return PersistentBST(new_root)
# ... recursion logic ...
# Demo
v1 = PersistentBST()
v2 = v1.insert(10)
v3 = v2.insert(5)
# Check v1 (empty), v2 (10), v3 (10, 5)
10. Final Polish:
- Ensure comments explain where the structural sharing happens.
- Highlight that memory usage is efficient because we aren't copying the whole tree, just the path from root to the changed node.
Let's write the actual response based on this plan. I will provide a Python implementation of a Persistent Binary Search Tree.
Self-Correction during drafting: Should I do a Persistent Hash Map? It's more "impressive" but requires bit-twiddling logic (HAMT) that is verbose. The BST is the pedagogical standard for this. I will stick to the BST.
I will also add a very small implementation of a Persistent List (Stack) at the beginning to ease the reader into the concept before doing the recursive tree.
Plan:
- Define Persistence (Immutability + Structural Sharing).
- Example 1: Persistent Stack (Simple linked list).
- Example 2: Persistent Binary Search Tree (Complex, structural sharing).
- Test code to prove old versions persist.
Let's go.
A Persistent Data Structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are immutable; instead of changing the existing data, operations return a new structure that shares most of its data with the old one (a technique called structural sharing).
Below is an implementation in Python. It demonstrates a Persistent Binary Search Tree.
The Concept: Path Copying
To make a tree persistent, we do not copy the entire tree for every update. We only copy the nodes along the path from the root to the modified node. All other branches point to the old nodes.
The Implementation (Python)
class TreeNode:
"""
A node in the Persistent Binary Search Tree.
It is immutable: once created, its value and children do not change.
"""
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 wrapper.
It holds a reference to the root of the current version.
"""
def __init__(self, root=None):
self.root = root
def insert(self, value):
"""
Inserts a value and returns a NEW PersistentBST instance
containing the change. The original tree remains untouched.
"""
new_root = self._insert_recursive(self.root, value)
return PersistentBST(new_root)
def _insert_recursive(self, node, value):
# Base case: If we reached a leaf (None), create a new node.
if node is None:
return TreeNode(value)
# If value is smaller, go left.
if value < node.value:
# RECURSION + PATH COPYING:
# We create a NEW node with the same value and right child,
# but the left child becomes the result of the recursive insert.
return TreeNode(
node.value,
self._insert_recursive(node.left, value),
node.right
)
# If value is larger, go right.
if value > node.value:
# RECURSION + PATH COPYING:
# We create a NEW node, preserving the left child,
# but replacing the right child.
return TreeNode(
node.value,
node.left,
self._insert_recursive(node.right, value)
)
# If value exists, return the existing node (no change needed).
return node
def contains(self, value):
"""Standard BST search (read-only)."""
return self._search(self.root, value)
def _search(self, node, value):
if node is None:
return False
if value == node.value:
return True
if value < node.value:
return self._search(node.left, value)
return self._search(node.right, value)
def print_tree(self):
"""Helper to print tree in-order."""
elements = []
self._inorder(self.root, elements)
return elements
def _inorder(self, node, acc):
if node:
self._inorder(node.left, acc)
acc.append(node.value)
self._inorder(node.right, acc)
# ==========================================
# Demonstration of Persistence
# ==========================================
if __name__ == "__main__":
print("--- Creating Version 1 ---")
# Create initial tree
v1 = PersistentBST()
v1 = v1.insert(50)
v1 = v1.insert(30)
v1 = v1.insert(70)
print(f"V1 contents: {v1.print_tree()}") # [30, 50, 70]
print("\n--- Creating Version 2 from V1 ---")
# Insert 20 into V1. This creates V2.
# V1 remains unchanged.
v2 = v1.insert(20)
print(f"V1 contents (unchanged): {v1.print_tree()}") # [30, 50, 70]
print(f"V2 contents (has 20): {v2.print_tree()}") # [20, 30, 50, 70]
print("\n--- Creating Version 3 from V1 ---")
# We can branch from any point in history.
# Insert 80 into V1 (not V2). This creates V3.
v3 = v1.insert(80)
print(f"V1 contents: {v1.print_tree()}") # [30, 50, 70]
print(f"V2 contents: {v2.print_tree()}") # [20, 30, 50, 70]
print(f"V3 contents: {v3.print_tree()}") # [30, 50, 70, 80]
print("\n--- Memory Verification (Structural Sharing) ---")
# In V1, the node 30 is the original object.
# In V2, the node 30 is a NEW object (copied path), but its children might be shared.
# However, the Root (50) was copied in both V2 and V3.
# Let's check object IDs to prove structural sharing.
# The 'left' child of V3 root (50) is 30.
# In V1, the 'left' child of root (50) is also 30.
# Since the path to 80 went Right, the Left subtree should be shared by ID.
print(f"V1 Root ID: {id(v1.root)}")
print(f"V2 Root ID: {id(v2.root)} (Different due to modification)")
print(f"V3 Root ID: {id(v3.root)} (Different due to modification)")
print("\nChecking shared nodes:")
# V3 modified the Right side. The Left side (Node 30) should be the exact same object in memory.
print(f"V1 Left Child (30) ID: {id(v1.root.left)}")
print(f"V3 Left Child (30) ID: {id(v3.root.left)}")
print(f"Are they the same object? {id(v1.root.left) == id(v3.root.left)}")
How it works
- Immutability: Notice that
TreeNode never has set_left or set_value methods.
- Path Copying: When we call
v1.insert(20):
- The recursion goes down the tree: 50 -> 30 -> None.
- It hits the base case and creates a new
Node(20).
- It returns to the call stack for
Node(30). It creates a new Node(30) pointing to the new Node(20).
- It returns to the call stack for
Node(50). It creates a new Node(50) pointing to the new Node(30).
- The old
Node(50) and Node(30) remain in memory, untouched.
- Structural Sharing: In the example of V3 (derived from V1 by inserting 80):
- We modified the right branch of the tree.
- The left branch (Node 30) was not touched. Therefore, V1 and V3 point to the exact same
Node(30) in memory. This makes the data structure memory efficient (O(logn) space for updates instead of O(n)).