Your task is to implement the Delete operation for a Byte-based Trie data structure (Prefix Tree) and verify its correctness in Lean. Postconditions: Functional Correctness (view(result) = view(tree) - {key}) and Invariant Preservation (result satisfies well-formedness and is not "empty"/useless). This requires "Eager Pruning": if deletion leaves a node with no children and not an endpoint, it must be removed.

import Mathlib

inductive Node
| mk (is_end : Bool) (children : List (Option Node))
deriving Inhabited

namespace Node

def is_end (t : Node) : Bool :=
  match t with
  | Node.mk b _ => b

def children (t : Node) : List (Option Node) :=
  match t with
  | Node.mk _ c => c

end Node

-- Helper for enum behavior
def enumerate {α} (l : List α) : List (Nat × α) :=
  (List.range l.length).zip l

def join {α} (l : List (List α)) : List α :=
  l.foldr List.append []

def flatMap {α β} (l : List α) (f : α → List β) : List β :=
  join (l.map f)

-- Using Set theory directly
def view (t : Node) : Set (List Int) :=
  let current : Set (List Int) := if t.is_end then {[]} else ∅
  let child_views : Set (List Int) :=
    let indexed_children := enumerate t.children
    indexed_children.foldr (fun (idx_child : Nat × Option Node) acc =>
      match idx_child.2 with
      | some child =>
        let suffix_set := view child
        let prefixed_set := suffix_set.image (fun suffix => (idx_child.1 : Int) :: suffix)
        acc ∪ prefixed_set
      | none => acc
    ) ∅
  current ∪ child_views
termination_by sizeOf t
decreasing_by sorry

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.children.all Option.isNone

-- Dafny uses an array of size 256. Here we model it as a list of 256 Option Node.
def well_formed (t : Node) : Prop :=
  match t with
  | Node.mk _ children =>
    children.length = 256 ∧
    ∀ c ∈ children, match c with
      | some child =>
          well_formed child ∧
          !is_empty_node child -- CRITICAL: Match Dafny/Verus Pruning requirement
      | none => True
termination_by sizeOf t
decreasing_by sorry

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

-- Precondition definitions
@[reducible, simp]
def delete_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
   | some node => well_formed node ∧ !is_empty_node node
   | none => True) ∧
  is_valid_key key -- Match Dafny/Verus input constraint
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def delete (t : Option Node) (key : List Int)
    (h_precond : delete_precond t key) : Option Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def delete_postcond (t : Option Node) (key : List Int) (result : Option Node)
    (_ : delete_precond t key) : Prop :=
  -- !benchmark @start postcond
  match result with
  | some res => well_formed res ∧ !is_empty_node res
  | none => True
  ∧
  view_opt result = view_opt t \ {key}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem delete_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : delete_precond t key) :
    delete_postcond t key (delete t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Insert operation for a Byte-based Trie data structure (Prefix Tree) and verify its correctness in Lean. The operation takes a tree (Option Node) and a key (List Int) and returns a new Node. Postconditions: Functional Correctness (view(result) = view(tree) + {key}), Well-Formedness (result is well-formed), and Non-Empty (result is not useless/empty). If the path does not exist, new nodes are allocated with 256 None children.

import Mathlib

inductive Node
| mk (is_end : Bool) (children : List (Option Node))
deriving Inhabited

namespace Node

def is_end (t : Node) : Bool :=
  match t with
  | Node.mk b _ => b

def children (t : Node) : List (Option Node) :=
  match t with
  | Node.mk _ c => c

end Node

-- Helper for enum behavior
def enumerate {α} (l : List α) : List (Nat × α) :=
  (List.range l.length).zip l

def join {α} (l : List (List α)) : List α :=
  l.foldr List.append []

def flatMap {α β} (l : List α) (f : α → List β) : List β :=
  join (l.map f)

-- Using Set theory directly
def view (t : Node) : Set (List Int) :=
  let current : Set (List Int) := if t.is_end then {[]} else ∅
  let child_views : Set (List Int) :=
    let indexed_children := enumerate t.children
    indexed_children.foldr (fun (idx_child : Nat × Option Node) acc =>
      match idx_child.2 with
      | some child =>
        let suffix_set := view child
        let prefixed_set := suffix_set.image (fun suffix => (idx_child.1 : Int) :: suffix)
        acc ∪ prefixed_set
      | none => acc
    ) ∅
  current ∪ child_views
termination_by sizeOf t
decreasing_by sorry

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.children.all Option.isNone

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

-- Dafny uses an array of size 256. Here we model it as a list of 256 Option Node.
def well_formed (t : Node) : Prop :=
  match t with
  | Node.mk _ children =>
    children.length = 256 ∧
    ∀ c ∈ children, match c with
      | some child =>
          well_formed child ∧
          !is_empty_node child -- CRITICAL: Match Dafny's pruning invariant
      | none => True
termination_by sizeOf t
decreasing_by sorry

-- Precondition definitions
@[reducible, simp]
def insert_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
  | some node => well_formed node ∧ !is_empty_node node
  | none => True) ∧
  is_valid_key key -- Added to match Dafny requirement
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def insert (t : Option Node) (key : List Int)
    (h_precond : insert_precond t key) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def insert_postcond (t : Option Node) (key : List Int) (result : Node)
    (_ : insert_precond t key) : Prop :=
  -- !benchmark @start postcond
  well_formed result ∧
  !is_empty_node result ∧
  view result = view_opt t ∪ {key}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem insert_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : insert_precond t key) :
    insert_postcond t key (insert t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Search operation for a Byte-based Trie data structure (Prefix Tree) and verify its correctness in Lean. The Trie represents keys as lists of bytes (integers 0-255). Postconditions: Functional Correctness (returns true iff key exists in the tree's view). Preconditions: Operation assumes the input tree satisfies well-formedness invariants (children array size 256, no useless nodes).

import Mathlib

inductive Node
| mk (is_end : Bool) (children : List (Option Node))
deriving Inhabited

namespace Node

def is_end (t : Node) : Bool :=
  match t with
  | Node.mk b _ => b

def children (t : Node) : List (Option Node) :=
  match t with
  | Node.mk _ c => c

end Node

-- Helper for enum behavior
def enumerate {α} (l : List α) : List (Nat × α) :=
  (List.range l.length).zip l

-- Using Set theory directly
def view (t : Node) : Set (List Int) :=
  let current : Set (List Int) := if t.is_end then {[]} else ∅
  let child_views : Set (List Int) :=
    let indexed_children := enumerate t.children
    indexed_children.foldr (fun (idx_child : Nat × Option Node) acc =>
      match idx_child.2 with
      | some child =>
        let suffix_set := view child
        let prefixed_set := suffix_set.image (fun suffix => (idx_child.1 : Int) :: suffix)
        acc ∪ prefixed_set
      | none => acc
    ) ∅
  current ∪ child_views
termination_by sizeOf t
decreasing_by sorry

-- Safe list access helper
def list_get_opt {α} (l : List α) (n : Nat) : Option α :=
  if h : n < l.length then some (l.get ⟨n, h⟩) else none

def contains (t : Node) (key : List Int) : Bool :=
  match key with
  | [] => t.is_end
  | c :: cs =>
    let children := t.children
      if c < children.length ∧ c ≥ 0 then
        match list_get_opt children c.toNat with
        | some (some child) => contains child cs
        | _ => false
      else
        false

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.children.all Option.isNone

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

@[reducible, simp]
def insert_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
  | some node => well_formed node ∧ !is_empty_node node
  | none => True) ∧
  is_valid_key key -- Added to match Dafny requirement
  -- !benchmark @end precond

-- Precondition definitions
@[reducible, simp]
def search_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
  | some node => well_formed node ∧ !is_empty_node node
  | none => True) ∧
  is_valid_key key -- Added to match Dafny
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def search (t : Option Node) (key : List Int)
    (h_precond : search_precond t key) : Bool :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def search_postcond (t : Option Node) (key : List Int) (result : Bool)
    (_ : search_precond t key) : Prop :=
  -- !benchmark @start postcond
  result = (key ∈ view_opt t)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem search_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : search_precond t key) :
    search_postcond t key (search t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Find operation for a Disjoint Set Union (Union-Find) data structure and verify its correctness in Lean. The find operation returns the representative root of the set containing element x and performs path compression. Postconditions: Returns the root of x, valid index, root is a root (parent[root] = root), and path compression (future lookups strictly faster/closer to root).

import Mathlib

structure UnionFind where
  parent : List Nat
  rank   : List Nat -- Added to match Dafny/Verus
deriving Inhabited

namespace UnionFind

def len (uf : UnionFind) : Nat := uf.parent.length

def is_valid (uf : UnionFind) : Prop :=
  uf.parent.length = uf.rank.length ∧
  ∀ i, i < uf.len →
    let p := uf.parent.getD i 0
    p < uf.len ∧
    uf.rank.getD i 0 < uf.len ∧
    -- CRITICAL: Rank monotonicity enforces acyclicity (DAG structure)
    (p ≠ i → uf.rank.getD i 0 < uf.rank.getD p 0)

-- Measure for termination proof, matching Dafny
def measure (uf : UnionFind) (i : Nat) : Nat :=
  if h : i < uf.len then
    uf.len - uf.rank.getD i 0
  else 0

-- The Abstract Model ("Ghost Spec")
def spec_find (uf : UnionFind) (i : Nat) : Nat :=
  if h : i < uf.len ∧ uf.rank.getD i 0 < uf.len then
    let p := uf.parent.getD i 0
    -- If not root and parent has higher rank (valid edge up)
    if p ≠ i ∧ p < uf.len ∧ uf.rank.getD i 0 < uf.rank.getD p 0 then
      spec_find uf p
    else
      i
  else
    i
termination_by measure uf i
decreasing_by sorry -- Dafny/Verus solve this automatically; Lean needs 'sorry' or manual proof

-- Precondition definitions
@[reducible, simp]
def find_precond (uf : UnionFind) (i : Nat) : Prop :=
  -- !benchmark @start precond
  uf.is_valid ∧ i < uf.len
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def find (uf : UnionFind) (i : Nat)
    (h_precond : find_precond uf i) : Nat × UnionFind :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def find_postcond (uf : UnionFind) (i : Nat) (result : Nat × UnionFind)
    (pre : find_precond uf i) : Prop :=
  -- !benchmark @start postcond
  let (root, new_uf) := result
  -- 1. Validity preservation
  new_uf.is_valid ∧
  -- 2. Functional Correctness: Returns the specific representative
  root = spec_find uf i ∧
  -- 3. Logical Stability: Path compression doesn't change sets
  (∀ j, j < uf.len → spec_find new_uf j = spec_find uf j) ∧
  -- 4. Structure: Length and Ranks preserved
  new_uf.len = uf.len ∧
  new_uf.rank = uf.rank
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem find_postcond_satisfied (uf : UnionFind) (i : Nat)
    (h_precond : find_precond uf i) :
    find_postcond uf i (find uf i h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof

end UnionFind


Your task is to implement the link_roots operation for a Union-Find data structure and verify its correctness in Lean. This operation merges two sets given their roots, using union-by-rank. Postconditions: The two roots now have the same representative, rank invariant is preserved, and other disjoint sets are unaffected.

import Mathlib

structure UnionFind where
  parent : List Nat
  rank   : List Nat
  len    : Nat
deriving Inhabited

namespace UnionFind

-- 1. Correct Invariant (Matches Dafny/Verus)
-- Must enforce rank monotonicity to prevent cycles.
def is_valid (uf : UnionFind) : Prop :=
  uf.parent.length = uf.len ∧
  uf.rank.length = uf.len ∧
  ∀ i, i < uf.len →
    let p := uf.parent.getD i 0
    p < uf.len ∧
    uf.rank.getD i 0 < uf.len ∧
    -- CRITICAL: Child rank must be strictly less than Parent rank (unless root)
    (p ≠ i → uf.rank.getD i 0 < uf.rank.getD p 0)

-- Measure for termination (Matches Dafny 'measure')
def measure (uf : UnionFind) (i : Nat) : Nat :=
  if h : i < uf.len then
    uf.len - uf.rank.getD i 0
  else 0

-- 2. Concrete Ghost Function (Matches Dafny 'spec_find')
-- We need this to define functional correctness.
def spec_find (uf : UnionFind) (i : Nat) : Nat :=
  if h : i < uf.len ∧ uf.rank.getD i 0 < uf.len then
    let p := uf.parent.getD i 0
    -- If valid parent exists with higher rank...
    if p ≠ i ∧ p < uf.len ∧ uf.rank.getD i 0 < uf.rank.getD p 0 then
      spec_find uf p
    else
      i
  else
    i
termination_by measure uf i
decreasing_by sorry

-- Precondition definitions
@[reducible, simp]
def link_roots_precond (uf : UnionFind) (root_i root_j : Nat) : Prop :=
  -- !benchmark @start precond
  uf.is_valid ∧
  root_i < uf.len ∧
  root_j < uf.len ∧
  uf.parent.getD root_i 0 = root_i ∧ -- Input i is a root
  uf.parent.getD root_j 0 = root_j    -- Input j is a root
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def link_roots (uf : UnionFind) (root_i root_j : Nat)
    (h_precond : link_roots_precond uf root_i root_j) : UnionFind :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def link_roots_postcond (uf : UnionFind) (root_i root_j : Nat) (result : UnionFind)
    (_ : link_roots_precond uf root_i root_j) : Prop :=
  -- !benchmark @start postcond
  result.is_valid ∧
  result.len = uf.len ∧
  -- Functional Correctness: The two trees are merged
  spec_find result root_i = spec_find result root_j ∧
  -- Frame Condition: Other roots must NOT change.
  -- (Matches Dafny: forall k ... old(parent)[k] == k ==> parent[k] == k)
  (∀ k, k < uf.len ∧ k ≠ root_i ∧ k ≠ root_j →
     uf.parent.getD k 0 = k → result.parent.getD k 0 = k)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem link_roots_postcond_satisfied (uf : UnionFind) (root_i root_j : Nat)
    (h_precond : link_roots_precond uf root_i root_j) :
    link_roots_postcond uf root_i root_j (link_roots uf root_i root_j h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof

end UnionFind