moon add SupremeHuaji/MaxStack // Create a new empty stack
let stack = @MaxStack.new()
// Create type-specific stacks using generics
let int_stack : MaxStack[Int] = @MaxStack.new()
let string_stack : MaxStack[String] = @MaxStack.new() let stack = @MaxStack.new()
.push(10)
.push(5)
.push(20)
.push(15)
// Stack now contains: [10, 5, 20, 15] (bottom to top) let stack = @MaxStack.new()
.push(10)
.push(20)
match stack.peek() {
Ok(value) => println("Top element: \{value}") // Output: Top element: 20
Err(StackError::EmptyStack) => println("Stack is empty")
} let stack = @MaxStack.new()
.push(10)
.push(20)
match stack.pop() {
Ok((value, new_stack)) => {
println("Popped element: \{value}") // Output: Popped element: 20
// new_stack is the stack after removing the element
}
Err(StackError::EmptyStack) => println("Stack is empty, cannot pop")
} let stack = @MaxStack.new()
.push(10)
.push(5)
.push(20)
.push(15)
match stack.get_max() {
Ok(max_value) => println("Maximum in stack: \{max_value}") // Output: Maximum in stack: 20
Err(StackError::EmptyStack) => println("Stack is empty, no maximum")
} let stack = @MaxStack.new()
.push(10)
.push(20)
// Check if stack is empty
if stack.is_empty() {
println("Stack is empty")
} else {
println("Stack is not empty")
}
// Get stack size
let size = stack.size()
println("Stack size: \{size}") // Output: Stack size: 2 // Integer stack
let int_stack = @MaxStack.new()
.push(100)
.push(50)
.push(200)
// Float stack
let float_stack = @MaxStack.new()
.push(10.5)
.push(20.3)
.push(15.7)
// String stack (lexicographic comparison)
let string_stack = @MaxStack.new()
.push("apple")
.push("banana")
.push("cherry") let result = @MaxStack.new()
.push(10)
.push(5)
.push(20)
.push(15)
match result.get_max() {
Ok(max) => println("Maximum: \{max}") // Output: Maximum: 20
Err(_) => println("Operation failed")
}
// Consecutive pop operations
let stack = @MaxStack.new()
.push(10)
.push(20)
.push(30)
match stack.pop() {
Ok((value1, stack1)) => {
println("First pop: \{value1}") // Output: First pop: 30
match stack1.pop() {
Ok((value2, stack2)) => {
println("Second pop: \{value2}") // Output: Second pop: 20
match stack2.get_max() {
Ok(max) => println("Remaining maximum: \{max}") // Output: Remaining maximum: 10
Err(_) => println("Stack is empty")
}
}
Err(_) => println("Second pop failed")
}
}
Err(_) => println("First pop failed")
} let empty_stack = @MaxStack.new()
// Operations on empty stack will return errors
match empty_stack.peek() {
Ok(value) => println("Top: \{value}")
Err(StackError::EmptyStack) => println("Error: Attempting to peek empty stack")
}
match empty_stack.pop() {
Ok((value, new_stack)) => println("Popped: \{value}")
Err(StackError::EmptyStack) => println("Error: Attempting to pop from empty stack")
}
match empty_stack.get_max() {
Ok(max) => println("Maximum: \{max}")
Err(StackError::EmptyStack) => println("Error: Attempting to get maximum from empty stack")
} // â
Good: Use method chaining for batch operations
let efficient_stack = @MaxStack.new()
.push(10)
.push(20)
.push(5)
.push(30)
// â
Good: Properly handle error cases
match stack.pop() {
Ok((value, new_stack)) => {
// Use value and new_stack for subsequent operations
process_value(value)
continue_with_stack(new_stack)
}
Err(StackError::EmptyStack) => {
// Handle empty stack case
handle_empty_stack()
}
}
// â
Good: Leverage O(1) maximum value query advantage
let stack = build_large_stack()
match stack.get_max() {
Ok(max) => println("Quickly found maximum in large stack: \{max}")
Err(_) => println("Stack is empty")
}| Method | Time Complexity | Description |
|---|---|---|
| new() | O(1) | Create new empty stack |
| Method | Time Complexity | Return Type | Description |
|---|---|---|---|
| push(value) | O(1) | MaxStack[T] | Push element, return new stack |
| pop() | O(1) | Result[(T, MaxStack[T]), StackError] | Pop top element |
| peek() | O(1) | Result[T, StackError] | View top element |
| get_max() | O(1) | Result[T, StackError] | Get maximum value in stack |
| Method | Time Complexity | Return Type | Description |
|---|---|---|---|
| is_empty() | O(1) | Bool | Check if stack is empty |
| size() | O(1) | Int | Get number of elements in stack |
| Error | Description |
|---|---|
| StackError::EmptyStack | Thrown when operating on empty stack |
| Operation | Time Complexity | Space Complexity | Description |
|---|---|---|---|
| new() | O(1) | O(1) | Create empty stack |
| push() | O(1) | O(1) | Push element |
| pop() | O(1) | O(1) | Pop element |
| peek() | O(1) | O(1) | View top |
| get_max() | O(1) | O(1) | Get maximum |
| is_empty() | O(1) | O(1) | Check if empty |
| size() | O(1) | O(1) | Get stack size |
pub(all) enum IterationOrder {
TopToBottom
BottomToTop
}println("Stack capacity: \{stack.capacity()}")stack.clear()
assert_eq!(stack.size(), 0)if stack.contains(42) {
println("Stack contains 42")
}let count = stack.count_if(fn(x) { x > 10 })
println("Number of elements > 10: \{count}")if stack1.equals(stack2) {
println("Stacks are equal")
}match stack.find(42) {
Some(index) => println("Found element at position \{index} from top")
None => println("Element not found")
}try {
let max_val = stack.force_get_max()!
println("Maximum value: \{max_val}")
} catch {
StackError::Underflow => println("Stack underflow")
}try {
let top = stack.force_peek()!
println("Top: \{top}")
} catch {
StackError::Underflow => println("Stack underflow")
}try {
let value = stack.force_pop()!
println("Popped: \{value}")
} catch {
StackError::Underflow => println("Stack underflow")
}try {
let popped = stack.force_pop_n(3)!
println("Popped elements: \{popped}")
} catch {
StackError::Underflow => println("Not enough elements in stack")
}match stack.get_max() {
StackResult::Success(max_val) => println("Maximum: \{max_val}")
StackResult::Empty => println("Stack is empty")
_ => {}
}match stack.get_min() {
StackResult::Success(min_val) => println("Minimum value: \{min_val}")
StackResult::Empty => println("Stack is empty")
_ => {}
}match stack.get_nth(2) {
StackResult::Success(value) => println("3rd element: \{value}")
StackResult::Empty => println("Stack empty or index out of bounds")
_ => {}
}if stack.is_empty() {
println("Stack is empty")
}if stack.is_full() {
println("Stack is full")
}stack.iter(IterationOrder::TopToBottom, fn(value) {
println("Element: \{value}")
})match stack.peek() {
StackResult::Success(value) => println("Top: \{value}")
StackResult::Empty => println("Stack is empty")
_ => {}
}match stack.pop() {
StackResult::Success(value) => println("Popped: \{value}")
StackResult::Empty => println("Stack is empty")
_ => {}
}let popped_values = stack.pop_n(3)let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!let results = stack.push_all([1, 2, 3])stack.resize()!let serialized = stack.serialize()println("Stack size: \{stack.size()}")let snapshot = stack.snapshot()
println("Snapshot timestamp: \{snapshot.timestamp}")match stack.state() {
StackState::Empty => println("Empty stack")
StackState::Normal => println("Normal")
StackState::NearFull => println("Nearly full")
StackState::Full => println("Full")
}let stats = stack.stats()
println("Usage ratio: \{stats.usage_ratio}")let arr = stack.to_array(IterationOrder::TopToBottom)match stack.try_force_pop() {
Ok(value) => println("Popped: \{value}")
Err(StackError::Underflow) => println("Stack is empty")
Err(error) => println("Other error: \{error}")
}pub struct MaxStackConfig {
initial_capacity : Int
auto_resize : Bool
growth_factor : Double
}impl Eq for MaxStackConfigimpl Show for MaxStackConfigimpl Eq for SerializedMaxStack[T]impl Show for SerializedMaxStack[T]impl Eq for StackSnapshot[T]impl Show for StackSnapshot[T]pub struct StackStats {
size : Int
capacity : Int
usage_ratio : Double
is_empty : Bool
is_full : Bool
}impl Eq for StackStatsimpl Show for StackStatslet stack = @MaxStack.default()let stack = @MaxStack.deserialize(serialized_data)!let stack = @MaxStack.from_array([3, 1, 4, 1, 5])let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)let config = MaxStackConfig::{ initial_capacity: 10, auto_resize: true, growth_factor: 2.0 }
match @MaxStack.try_new(config) {
Ok(stack) => println("Creation successful")
Err(error) => println("Creation failed: \{error}")
}