Zulip Chat Archive

Stream: Is there code for X?

Topic: a stack?


JJ (Aug 16 2025 at 03:50):

Is there a standard last-in first-out data structure in the standard library?

Kim Morrison (Aug 16 2025 at 04:12):

List? :-)

JJ (Aug 16 2025 at 04:16):

Ha, maybe :-D

I would need a way to index backwards into it. Unfortunately, Loogling List ?a -> Nat -> Option ?a only finds List.get?. I can't just do foo[foo.length - n - 1]on account of subtraction bottoming out at zero.

Is there any nice notation for this, like foo[^idx] or the like? My peek? function is currently very ugly, lol.

JJ (Aug 16 2025 at 04:24):

namespace Array
def peekn? (env : Array α) n :=
  if n >= env.size then none else env[env.size - n - 1]?
notation array "[^" n "]?" => Array.peekn? array n
end Array

#eval #[1, 2, 3][^0]? -- some 3

I guess that's not bad!

Anthony Fernandes (Aug 16 2025 at 19:24):

Does you application really need backward indexing? If no, something like this do the trick (maybe with Stack as a structure to provide a bit more separation between it and List)

abbrev Stack := List

namespace Stack

variable {α : Type}

def empty : Stack α := []

def of_list : List α  Stack α := id

def push (x : α) (s : Stack α) : Stack α := x :: s

def pop? : Stack α  Option α × Stack α
| [] => (none, [])
| x :: xs => (x, xs)

def peek? (s : Stack α) : Option α := s[0]?

def is_empty (s : Stack α) : Prop := s = []

end Stack

Last updated: Dec 20 2025 at 21:32 UTC