ilusm.dev

stk

Stack (LIFO) data structure - create an empty stack, push a value onto the top, pop returning the top value and the remaining stack, peek the top without modifying, query size, and clear.

Load with: use stk

What this module does

stk implements a last-in-first-out stack using an ilusm list where the head element (index 0) is always the top. Push prepends an element; pop returns an object {top, rest} so both the removed value and the remaining stack are available. The stack is an immutable value - all operations return new stacks.

Quick example

use stk

s = stkne()           # empty stack
s = stkpu(s, 10)
s = stkpu(s, 20)
s = stkpu(s, 30)

prn(stkpk(s))         # 30 (peek top)
prn(stksz(s))         # 3

r = stkpo(s)          # pop
prn(r.top)            # 30
s = r.rest            # [20, 10]

s = stkcl()           # empty stack

Functions

Stack operations

stkne()

Returns an empty stack (empty list).

stkpu(s, x)

Pushes x onto the top of stack s. Returns a new stack with x at position 0.

stkpo(s)

Pops the top element. Returns {top, rest} where top is the removed element and rest is the remainder. Throws "stk.pop: empty" if the stack is empty.

stkpk(s)

Returns the top element without removing it, or nil if the stack is empty.

stksz(s)

Returns the number of elements in the stack.

stkcl()

Returns an empty stack.

Notes

  • Requires trl.