Pure Nim stack implementation based on sequences.
Example:
# Reverting a string using a stack import stacks let a = "Hello, World!" var s = Stack[char]() for letter in a: s.push(letter) var b: string while not s.isEmpty: b.add(s.pop) assert b == "!dlroW ,olleH"
Types
EStackEmpty = object of CatchableError
Stack[T] = object data: seq[T]
Procs
proc newStack[T](capacity = 8): Stack[T]
-
Creates a new stack. Optionally, the initial capacity can be reserved via capacity parameter.
var a = newStack[int](capacity = 64)
proc len[T](s: Stack[T]): int
-
Returns the number of elements in the stack. Returns 0 if the stack is empty.
var a = newStack[int]() assert a.len == 0 a.push(10); a.push(20) assert a.len == 2
proc empty[T](s: Stack[T]): bool {...}{.deprecated: "use isEmpty() instead".}
proc isEmpty[T](s: Stack[T]): bool
-
Returns true if stack contains no elements, false otherwise.
var a = newStack[int]() assert a.isEmpty == true a.push(10) assert a.isEmpty == false
proc push[T](s: var Stack[T]; element: T)
-
Pushes element onto the top of the stack.
var a = newStack[int]() a.push(10)
proc pop[T](s: var Stack[T]): T {...}{.raises: [EStackEmpty].}
-
Pops the top element from the stack. Raises EStackEmpty exception if the stack is empty.
var a = newStack[int]() a.push(10) discard a.pop() doAssertRaises(EStackEmpty, echo a.pop())
proc popUnsafe[T](s: var Stack[T]): T
-
Pops the top element from the stack without checking if it's not empty. Make sure the stack is not empty.
var a = newStack[int]() a.push(10) check(a.popUnsafe() == 10)
proc peek[T](s: Stack[T]): T {...}{.raises: [EStackEmpty].}
-
Peeks the top element from the stack. Raises EStackEmpty exception if the stack is empty.
var a = newStack[int]() a.push(10) check(a.peek() == 10)
proc peekUnsafe[T](s: Stack[T]): T
-
Peeks the top element from the stack without checking if it's not empty. Make sure the stack is not empty.
var a = newStack[int]() a.push(10) check(a.peekUnsafe() == 10)
proc clear[T](s: var Stack[T])
-
Empties the stack. Does nothing if the stack is already empty.
var a = newStack[int]() a.push(10) a.clear() assert a.isEmpty == true
proc toSeq[T](s: Stack[T]): seq[T]
-
Returns sequence representation of a stack.
var a = newStack[int]() a.push(10); a.push(20) assert a.toSeq() == @[10, 20]
proc `$`[T](s: Stack[T]): string
-
Returns string representation of a stack
var a = newStack[int]() a.push(10); a.push(20) assert $a == "Stack[10, 20]"