Lean4
/-- Nest `p` in one pair of brackets, i.e. `x` becomes `(x)`. -/
def nest : DyckWord where
toList := [U] ++ p ++ [D]
count_U_eq_count_D := by simp [p.count_U_eq_count_D]
count_D_le_count_U
i := by
simp only [take_append, count_append]
rw [← add_rotate (count D _), ← add_rotate (count U _)]
apply add_le_add _ (p.count_D_le_count_U _)
rcases i.eq_zero_or_pos with hi | hi; · simp [hi]
rw [take_of_length_le (show [U].length ≤ i by rwa [length_singleton]), count_singleton']
simp only [reduceCtorEq, ite_false]
rw [add_comm]
exact add_le_add (zero_le _) (count_le_length.trans (by simp))