Skip to content

Commit

Permalink
feat: add push and pop
Browse files Browse the repository at this point in the history
  • Loading branch information
fgdorais committed May 28, 2024
1 parent 10d0530 commit c8d001c
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Batteries/Data/DArray.lean
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ private unsafe def umodifyFImpl [Functor f] (a : DArray n α) (i : USize) (h : i
let a := unsafeCast <| a.data.uset i (unsafeCast ()) lcProof
usetImpl a i h <$> t v

private unsafe def pushImpl (a : DArray n α) (v : β) :
DArray (n+1) fun i => if h : i.val < n then α ⟨i.val, h⟩ else β :=
unsafeCast <| a.data.push <| unsafeCast v

private unsafe def popImpl (a : DArray (n+1) α) : DArray n fun i => α i.castSucc :=
unsafeCast <| a.data.pop

private unsafe def copyImpl (a : DArray n α) : DArray n α :=
unsafeCast <| a.data.extract 0 n

Expand Down Expand Up @@ -136,6 +143,17 @@ protected abbrev umodify (a : DArray n α) (i : USize) (h : i.toNat < n)
@[implemented_by copyImpl]
protected def copy (a : DArray n α) : DArray n α := mk a.get

/-- Push an element onto the end of a `DArray`. `O(1)` if exclusive else `O(n)`. -/
@[implemented_by pushImpl]
protected def push (a : DArray n α) (v : β) :
DArray (n+1) fun i => if h : i.val < n then α ⟨i.val, h⟩ else β :=
mk fun i => if h : i.val < n then dif_pos h ▸ a.get ⟨i.val, h⟩ else dif_neg h ▸ v

/-- Delete the last item of a `DArray`. `O(1)` if exclusive else `O(n)`. -/
@[implemented_by popImpl]
protected def pop (a : DArray (n+1) α) : DArray n fun i => α i.castSucc :=
mk fun i => a.get i.castSucc

@[ext]
protected theorem ext : {a b : DArray n α} → (∀ i, a.get i = b.get i) → a = b
| mk _, mk _, h => congrArg _ <| funext fun i => h i
Expand Down

0 comments on commit c8d001c

Please sign in to comment.