Data Structures19 sections · 729 units
Open in Course

Copy-on-Write Semantics

Delayed copying

Copy-on-write (CoW) is a persistence technique:

  • Share data between versions until modification
  • Copy only when writing

Used in operating systems (fork), databases (snapshots), and functional programming.

// Copy-on-write with immutable patterns
function update_tree(node, path, value):
    if path is empty:
        return new Node(value, node.left, node.right)  // new node
    if path[0] == "L":
        return new Node(node.value,
            update_tree(node.left, path[1:], value),
            node.right)  // share right
    else:
        return new Node(node.value,
            node.left,
            update_tree(node.right, path[1:], value))  // share left

This is exactly path copying. CoW is the general principle; path copying is the tree-specific implementation.