Skip to content

Instantly share code, notes, and snippets.

@gabyfle
Last active March 24, 2021 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabyfle/b770b23c541280c29da39f0daa3e49b3 to your computer and use it in GitHub Desktop.
Save gabyfle/b770b23c541280c29da39f0daa3e49b3 to your computer and use it in GitHub Desktop.
Stack by array
let lmax = 100
type 'a stack = { tab: 'a array; mutable length: int }
let empty default =
{ tab = Array.make lmax default; length = 0 }
let push x stack = match stack with
| { tab = _; length = 100 } -> failwith "Stack overflow"
| { tab = t; length = n } -> t.(n + 1) <- x; stack.length <- n + 1
let pop stack = match stack with
| { tab = _; length = 0 } -> failwith "Stack underflow" (* lol *)
| { tab = t; length = n } -> stack.length <- n - 1; t.(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment