1///|
2/// Stack error types
3type! StackError {
4 /// Stack underflow (pop operation on empty stack)
5 StackError
Stack underflow (pop operation on empty stack)
Underflow
6 /// Stack overflow (push operation on full stack)
7 StackError
Stack overflow (push operation on full stack)
Overflow
8 /// Invalid capacity
9 (Int) -> StackError
Invalid capacity
InvalidCapacity(Int
Int)
10 /// Invalid configuration parameter
11 (String) -> StackError
Invalid configuration parameter
InvalidConfig(String
String)
12}
13
14///|
15/// Create a new MaxStack
16///
17/// # Example
18/// ```
19/// let config = MaxStackConfig::{
20/// initial_capacity: 10,
21/// auto_resize: true,
22/// growth_factor: 2.0
23/// }
24/// let stack = @MaxStack.new(config)
25/// ```
26pub fn (config : MaxStackConfig) -> MaxStack[T] raise Error
Create a new MaxStack
Example
let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)
new[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStackConfig
config : struct MaxStackConfig {
initial_capacity: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack configuration parameters
MaxStackConfig) -> struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]! {
27 if MaxStackConfig
config.Int
Initial capacity
initial_capacity (self_ : Int, other : Int) -> Bool
<= 0 {
28 raise StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(MaxStackConfig
config.Int
Initial capacity
initial_capacity)
29 }
30 if MaxStackConfig
config.Double
Growth factor (used when auto_resize is true)
growth_factor (self_ : Double, other : Double) -> Bool
<= 1.0 {
31 raise StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig("Growth factor must be greater than 1.0")
32 }
33 {
34 Array[T?]
Data stack, stores actual elements
data_stack: type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array::(Int, T?) -> Array[T?]
Creates a new array with a specified length and initializes all elements with
the given value.
Parameters:
length : The length of the array to create. Must be a non-negative
integer.
initial_value : The value used to initialize all elements in the array.
Returns a new array of type Array[T] with length elements, where each
element is initialized to initial_value.
Throws an error if length is negative.
Example:
let arr = Array::make(3, 42)
inspect(arr, content="[42, 42, 42]")
WARNING: A common pitfall is creating with the same initial value, for example:
let two_dimension_array = Array::make(10, Array::make(10, 0))
two_dimension_array[0][5] = 10
assert_eq(two_dimension_array[5][5], 10)
This is because all the cells reference to the same object (the Array[Int] in this case).
One should use makei() instead which creates an object for each index.
make(MaxStackConfig
config.Int
Initial capacity
initial_capacity, T?
None),
35 Array[T?]
Max stack, stores the maximum value at each position
max_stack: type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array::(Int, T?) -> Array[T?]
Creates a new array with a specified length and initializes all elements with
the given value.
Parameters:
length : The length of the array to create. Must be a non-negative
integer.
initial_value : The value used to initialize all elements in the array.
Returns a new array of type Array[T] with length elements, where each
element is initialized to initial_value.
Throws an error if length is negative.
Example:
let arr = Array::make(3, 42)
inspect(arr, content="[42, 42, 42]")
WARNING: A common pitfall is creating with the same initial value, for example:
let two_dimension_array = Array::make(10, Array::make(10, 0))
two_dimension_array[0][5] = 10
assert_eq(two_dimension_array[5][5], 10)
This is because all the cells reference to the same object (the Array[Int] in this case).
One should use makei() instead which creates an object for each index.
make(MaxStackConfig
config.Int
Initial capacity
initial_capacity, T?
None),
36 Int
Current stack size
size: 0,
37 Bool
Whether auto-resize is enabled
auto_resize: MaxStackConfig
config.Bool
Whether auto-resize is enabled
auto_resize,
38 Double
Growth factor (used when auto_resize is true)
growth_factor: MaxStackConfig
config.Double
Growth factor (used when auto_resize is true)
growth_factor,
39 }
40}
41
42///|
43/// Create a MaxStack with default configuration
44///
45/// # Example
46/// ```
47/// let stack = @MaxStack.default()
48/// ```
49pub fn () -> MaxStack[T] raise Error
Create a MaxStack with default configuration
Example
let stack = @MaxStack.default()
default[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare]() -> struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]! {
50 let MaxStackConfig
config = struct MaxStackConfig {
initial_capacity: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack configuration parameters
MaxStackConfig::{
51 Int
Initial capacity
initial_capacity: 16,
52 Bool
Whether auto-resize is enabled
auto_resize: true,
53 Double
Growth factor (used when auto_resize is true)
growth_factor: 2.0,
54 }
55 (config : MaxStackConfig) -> MaxStack[T] raise Error
Create a new MaxStack
Example
let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)
new!(MaxStackConfig
config)
56}
57
58///|
59/// Create a MaxStack from an array
60///
61/// # Example
62/// ```
63/// let stack = @MaxStack.from_array([3, 1, 4, 1, 5])
64/// ```
65pub fn (arr : Array[T]) -> MaxStack[T] raise Error
Create a MaxStack from an array
Example
let stack = @MaxStack.from_array([3, 1, 4, 1, 5])
from_array[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](Array[T]
arr : type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[type parameter T
T]) -> struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]! {
66 let MaxStackConfig
config = struct MaxStackConfig {
initial_capacity: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack configuration parameters
MaxStackConfig::{
67 Int
Initial capacity
initial_capacity: if Array[T]
arr.(self : Array[T]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length() (self_ : Int, other : Int) -> Bool
> 16 {
68 Array[T]
arr.(self : Array[T]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length()
69 } else {
70 16
71 },
72 Bool
Whether auto-resize is enabled
auto_resize: true,
73 Double
Growth factor (used when auto_resize is true)
growth_factor: 2.0,
74 }
75 let MaxStack[T]
stack = (config : MaxStackConfig) -> MaxStack[T] raise Error
Create a new MaxStack
Example
let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)
new!(MaxStackConfig
config)
76 for T
item in Array[T]
arr {
77 MaxStack[T]
stack.(self : MaxStack[T], value : T) -> Unit raise Error
Push an element onto the stack
Example
let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!
push!(T
item)
78 }
79 MaxStack[T]
stack
80}
81
82///|
83/// Push an element onto the stack
84///
85/// # Example
86/// ```
87/// let stack = @MaxStack.default()
88/// stack.push(42)!
89/// stack.push(24)!
90/// ```
91pub fn (self : MaxStack[T], value : T) -> Unit raise Error
Push an element onto the stack
Example
let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!
push[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], T
value : type parameter T
T) -> Unit
Unit! {
92 if MaxStack[T]
self.Int
Current stack size
size (self_ : Int, other : Int) -> Bool
>= MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack.(self : Array[T?]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length() {
93 if MaxStack[T]
self.Bool
Whether auto-resize is enabled
auto_resize (self : Bool, other : Bool) -> Bool
Compares two boolean values for equality.
Parameters:
self : The first boolean value to compare.
other : The second boolean value to compare.
Returns true if both boolean values are equal (either both true or both
false), false otherwise.
Example:
inspect(true == true, content="true")
inspect(false == true, content="false")
inspect(true == false, content="false")
inspect(false == false, content="true")
== false {
94 raise StackError::StackError
Stack overflow (push operation on full stack)
Overflow
95 }
96 MaxStack[T]
self.(self : MaxStack[T]) -> Unit raise Error
Resize the stack capacity
Example
stack.resize()!
resize!()
97 }
98
99 // Push to data stack
100 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = (T) -> T?
Some(T
value)
101
102 // Calculate and push to max stack
103 let T
new_max = if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
104 T
value
105 } else {
106 let T
current_max = MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
107 if T
value (self_ : T, other : T) -> Bool
> T
current_max {
108 T
value
109 } else {
110 T
current_max
111 }
112 }
113 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = (T) -> T?
Some(T
new_max)
114 MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+= 1
115}
116
117///|
118/// Pop an element from the stack
119///
120/// # Example
121/// ```
122/// match stack.pop() {
123/// StackResult::Success(value) => println("Popped: \{value}")
124/// StackResult::Empty => println("Stack is empty")
125/// _ => {}
126/// }
127/// ```
128pub fn (self : MaxStack[T]) -> StackResult[T]
Pop an element from the stack
Example
match stack.pop() {
StackResult::Success(value) => println("Popped: \{value}")
StackResult::Empty => println("Stack is empty")
_ => {}
}
pop[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum StackResult[T] {
Success(T)
Empty
Full
}
Stack operation result type
StackResult[type parameter T
T] {
129 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
130 return StackResult::StackResult[T]
Stack is empty, operation failed
Empty
131 }
132 MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
-= 1
133 let T
value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
134
135 // Clear values at corresponding position
136 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = T?
None
137 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = T?
None
138 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
value)
139}
140
141///|
142/// Get the top element (without popping)
143///
144/// # Example
145/// ```
146/// match stack.peek() {
147/// StackResult::Success(value) => println("Top: \{value}")
148/// StackResult::Empty => println("Stack is empty")
149/// _ => {}
150/// }
151/// ```
152pub fn (self : MaxStack[T]) -> StackResult[T]
Get the top element (without popping)
Example
match stack.peek() {
StackResult::Success(value) => println("Top: \{value}")
StackResult::Empty => println("Stack is empty")
_ => {}
}
peek[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum StackResult[T] {
Success(T)
Empty
Full
}
Stack operation result type
StackResult[type parameter T
T] {
153 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
154 return StackResult::StackResult[T]
Stack is empty, operation failed
Empty
155 }
156 let T
value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
157 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
value)
158}
159
160///|
161/// Get the current maximum value
162///
163/// # Example
164/// ```
165/// match stack.get_max() {
166/// StackResult::Success(max_val) => println("Maximum: \{max_val}")
167/// StackResult::Empty => println("Stack is empty")
168/// _ => {}
169/// }
170/// ```
171pub fn (self : MaxStack[T]) -> StackResult[T]
Get the current maximum value
Example
match stack.get_max() {
StackResult::Success(max_val) => println("Maximum: \{max_val}")
StackResult::Empty => println("Stack is empty")
_ => {}
}
get_max[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum StackResult[T] {
Success(T)
Empty
Full
}
Stack operation result type
StackResult[type parameter T
T] {
172 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
173 return StackResult::StackResult[T]
Stack is empty, operation failed
Empty
174 }
175 let T
max_value = MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
176 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
max_value)
177}
178
179///|
180/// Get the size of the stack
181///
182/// # Example
183/// ```
184/// println("Stack size: \{stack.size()}")
185/// ```
186pub fn (self : MaxStack[T]) -> Int
Get the size of the stack
Example
println("Stack size: \{stack.size()}")
size[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Int
Int {
187 MaxStack[T]
self.Int
Current stack size
size
188}
189
190///|
191/// Check if the stack is empty
192///
193/// # Example
194/// ```
195/// if stack.is_empty() {
196/// println("Stack is empty")
197/// }
198/// ```
199pub fn (self : MaxStack[T]) -> Bool
Check if the stack is empty
Example
if stack.is_empty() {
println("Stack is empty")
}
is_empty[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Bool
Bool {
200 MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0
201}
202
203///|
204/// Check if the stack is full
205///
206/// # Example
207/// ```
208/// if stack.is_full() {
209/// println("Stack is full")
210/// }
211/// ```
212pub fn (self : MaxStack[T]) -> Bool
Check if the stack is full
Example
if stack.is_full() {
println("Stack is full")
}
is_full[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Bool
Bool {
213 MaxStack[T]
self.Int
Current stack size
size (self_ : Int, other : Int) -> Bool
>= MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack.(self : Array[T?]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length()
214}
215
216///|
217/// Clear the stack
218///
219/// # Example
220/// ```
221/// stack.clear()
222/// assert_eq!(stack.size(), 0)
223/// ```
224pub fn (self : MaxStack[T]) -> Unit
Clear the stack
Example
stack.clear()
assert_eq!(stack.size(), 0)
clear[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Unit
Unit {
225 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
226 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = T?
None
227 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = T?
None
228 }
229 MaxStack[T]
self.Int
Current stack size
size = 0
230}
231
232///|
233/// Get the capacity of the stack
234///
235/// # Example
236/// ```
237/// println("Stack capacity: \{stack.capacity()}")
238/// ```
239pub fn (self : MaxStack[T]) -> Int
Get the capacity of the stack
Example
println("Stack capacity: \{stack.capacity()}")
capacity[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Int
Int {
240 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack.(self : Array[T?]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length()
241}
242
243///|
244/// Get stack statistics
245///
246/// # Example
247/// ```
248/// let stats = stack.stats()
249/// println("Usage ratio: \{stats.usage_ratio}")
250/// ```
251pub fn (self : MaxStack[T]) -> StackStats
Get stack statistics
Example
let stats = stack.stats()
println("Usage ratio: \{stats.usage_ratio}")
stats[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> struct StackStats {
size: Int
capacity: Int
usage_ratio: Double
is_empty: Bool
is_full: Bool
}
Stack statistics
StackStats {
252 let Int
cap = MaxStack[T]
self.(self : MaxStack[T]) -> Int
Get the capacity of the stack
Example
println("Stack capacity: \{stack.capacity()}")
capacity()
253 {
254 Int
Current number of elements
size: MaxStack[T]
self.Int
Current stack size
size,
255 Int
Stack capacity
capacity: Int
cap,
256 Double
Usage ratio
usage_ratio: if Int
cap (self_ : Int, other : Int) -> Bool
> 0 {
257 MaxStack[T]
self.Int
Current stack size
size.(self : Int) -> Double
Converts a 32-bit integer to a double-precision floating-point number. The
conversion preserves the exact value since all integers in the range of Int
can be represented exactly as Double values.
Parameters:
self : The 32-bit integer to be converted.
Returns a double-precision floating-point number that represents the same
numerical value as the input integer.
Example:
let n = 42
inspect(n.to_double(), content="42")
let neg = -42
inspect(neg.to_double(), content="-42")
to_double() (self : Double, other : Double) -> Double
Performs division between two double-precision floating-point numbers.
Follows IEEE 754 standard for floating-point arithmetic, including handling
of special cases like division by zero (returns infinity) and operations
involving NaN.
Parameters:
self : The dividend (numerator) in the division operation.
other : The divisor (denominator) in the division operation.
Returns the result of dividing self by other. Special cases follow IEEE
754:
- Division by zero returns positive or negative infinity based on the
dividend's sign
- Operations involving NaN return NaN
- Division of infinity by infinity returns NaN
Example:
inspect(6.0 / 2.0, content="3")
inspect(-6.0 / 2.0, content="-3")
inspect(1.0 / 0.0, content="Infinity")
/ Int
cap.(self : Int) -> Double
Converts a 32-bit integer to a double-precision floating-point number. The
conversion preserves the exact value since all integers in the range of Int
can be represented exactly as Double values.
Parameters:
self : The 32-bit integer to be converted.
Returns a double-precision floating-point number that represents the same
numerical value as the input integer.
Example:
let n = 42
inspect(n.to_double(), content="42")
let neg = -42
inspect(neg.to_double(), content="-42")
to_double()
258 } else {
259 0.0
260 },
261 Bool
Whether stack is empty
is_empty: MaxStack[T]
self.(self : MaxStack[T]) -> Bool
Check if the stack is empty
Example
if stack.is_empty() {
println("Stack is empty")
}
is_empty(),
262 Bool
Whether stack is full
is_full: MaxStack[T]
self.(self : MaxStack[T]) -> Bool
Check if the stack is full
Example
if stack.is_full() {
println("Stack is full")
}
is_full(),
263 }
264}
265
266///|
267/// Get the current state of the stack
268///
269/// # Example
270/// ```
271/// match stack.state() {
272/// StackState::Empty => println("Empty stack")
273/// StackState::Normal => println("Normal")
274/// StackState::NearFull => println("Nearly full")
275/// StackState::Full => println("Full")
276/// }
277/// ```
278pub fn (self : MaxStack[T]) -> StackState
Get the current state of the stack
Example
match stack.state() {
StackState::Empty => println("Empty stack")
StackState::Normal => println("Normal")
StackState::NearFull => println("Nearly full")
StackState::Full => println("Full")
}
state[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum StackState {
Empty
Normal
NearFull
Full
}
Stack state enumeration
StackState {
279 if MaxStack[T]
self.(self : MaxStack[T]) -> Bool
Check if the stack is empty
Example
if stack.is_empty() {
println("Stack is empty")
}
is_empty() {
280 StackState::StackState
Empty stack state
Empty
281 } else if MaxStack[T]
self.(self : MaxStack[T]) -> Bool
Check if the stack is full
Example
if stack.is_full() {
println("Stack is full")
}
is_full() {
282 StackState::StackState
Full state
Full
283 } else {
284 let Double
usage = MaxStack[T]
self.(self : MaxStack[T]) -> StackStats
Get stack statistics
Example
let stats = stack.stats()
println("Usage ratio: \{stats.usage_ratio}")
stats().Double
Usage ratio
usage_ratio
285 if Double
usage (self_ : Double, other : Double) -> Bool
> 0.8 {
286 StackState::StackState
Near-full state (usage ratio > 80%)
NearFull
287 } else {
288 StackState::StackState
Normal state
Normal
289 }
290 }
291}
292
293///|
294/// Resize the stack capacity
295///
296/// # Example
297/// ```
298/// stack.resize()!
299/// ```
300pub fn (self : MaxStack[T]) -> Unit raise Error
Resize the stack capacity
Example
stack.resize()!
resize[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Unit
Unit! {
301 let Int
old_capacity = MaxStack[T]
self.(self : MaxStack[T]) -> Int
Get the capacity of the stack
Example
println("Stack capacity: \{stack.capacity()}")
capacity()
302 let Int
new_capacity = (Int
old_capacity.(self : Int) -> Double
Converts a 32-bit integer to a double-precision floating-point number. The
conversion preserves the exact value since all integers in the range of Int
can be represented exactly as Double values.
Parameters:
self : The 32-bit integer to be converted.
Returns a double-precision floating-point number that represents the same
numerical value as the input integer.
Example:
let n = 42
inspect(n.to_double(), content="42")
let neg = -42
inspect(neg.to_double(), content="-42")
to_double() (self : Double, other : Double) -> Double
Multiplies two double-precision floating-point numbers. This is the
implementation of the * operator for Double type.
Parameters:
self : The first double-precision floating-point operand.
other : The second double-precision floating-point operand.
Returns a new double-precision floating-point number representing the product
of the two operands. Special cases follow IEEE 754 standard:
- If either operand is NaN, returns NaN
- If one operand is infinity and the other is zero, returns NaN
- If one operand is infinity and the other is a non-zero finite number,
returns infinity with the appropriate sign
- If both operands are infinity, returns infinity with the appropriate sign
Example:
inspect(2.5 * 2.0, content="5")
inspect(-2.0 * 3.0, content="-6")
let nan = 0.0 / 0.0 // NaN
inspect(nan * 1.0, content="NaN")
* MaxStack[T]
self.Double
Growth factor (used when auto_resize is true)
growth_factor).(self : Double) -> Int
Converts a double-precision floating-point number to a 32-bit integer.
Handles special cases including NaN and numbers outside the valid Int range.
Parameters:
self : The double-precision floating-point number to be converted.
Returns an 32-bit integer value according to the following rules:
- Returns 0 if the input is NaN
- Returns
@int.max_value (2147483647) if the input is greater than or
equal to @int.max_value
- Returns
@int.min_value (-2147483648) if the input is less than or equal
to @int.min_value
- Otherwise returns the integer part of the input by truncating towards zero
Example:
inspect(42.0.to_int(), content="42")
inspect((-42.5).to_int(), content="-42")
inspect((0.0 / 0.0).to_int(), content="0") // NaN
inspect((1.0 / 0.0).to_int(), content="2147483647") // Infinity
inspect((-1.0 / 0.0).to_int(), content="-2147483648") // -Infinity
to_int()
303 if Int
new_capacity (self_ : Int, other : Int) -> Bool
<= Int
old_capacity {
304 raise StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
new_capacity)
305 }
306 let Array[T?]
new_data_stack = type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array::(Int, T?) -> Array[T?]
Creates a new array with a specified length and initializes all elements with
the given value.
Parameters:
length : The length of the array to create. Must be a non-negative
integer.
initial_value : The value used to initialize all elements in the array.
Returns a new array of type Array[T] with length elements, where each
element is initialized to initial_value.
Throws an error if length is negative.
Example:
let arr = Array::make(3, 42)
inspect(arr, content="[42, 42, 42]")
WARNING: A common pitfall is creating with the same initial value, for example:
let two_dimension_array = Array::make(10, Array::make(10, 0))
two_dimension_array[0][5] = 10
assert_eq(two_dimension_array[5][5], 10)
This is because all the cells reference to the same object (the Array[Int] in this case).
One should use makei() instead which creates an object for each index.
make(Int
new_capacity, T?
None)
307 let Array[T?]
new_max_stack = type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array::(Int, T?) -> Array[T?]
Creates a new array with a specified length and initializes all elements with
the given value.
Parameters:
length : The length of the array to create. Must be a non-negative
integer.
initial_value : The value used to initialize all elements in the array.
Returns a new array of type Array[T] with length elements, where each
element is initialized to initial_value.
Throws an error if length is negative.
Example:
let arr = Array::make(3, 42)
inspect(arr, content="[42, 42, 42]")
WARNING: A common pitfall is creating with the same initial value, for example:
let two_dimension_array = Array::make(10, Array::make(10, 0))
two_dimension_array[0][5] = 10
assert_eq(two_dimension_array[5][5], 10)
This is because all the cells reference to the same object (the Array[Int] in this case).
One should use makei() instead which creates an object for each index.
make(Int
new_capacity, T?
None)
308
309 // Copy existing data
310 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
311 Array[T?]
new_data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i]
312 Array[T?]
new_max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i]
313 }
314 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack = Array[T?]
new_data_stack
315 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack = Array[T?]
new_max_stack
316}
317
318///|
319/// Iterate through elements in the stack
320///
321/// # Example
322/// ```
323/// stack.iter(IterationOrder::TopToBottom, fn(value) {
324/// println("Element: \{value}")
325/// })
326/// ```
327pub fn (self : MaxStack[T], order : IterationOrder, f : (T) -> Unit) -> Unit
Iterate through elements in the stack
Example
stack.iter(IterationOrder::TopToBottom, fn(value) {
println("Element: \{value}")
})
iter[T](
328 MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T],
329 IterationOrder
order : enum IterationOrder {
TopToBottom
BottomToTop
}
Stack iteration direction
IterationOrder,
330 (T) -> Unit
f : (type parameter T
T) -> Unit
Unit
331) -> Unit
Unit {
332 match IterationOrder
order {
333 IterationOrder::IterationOrder
From top to bottom (LIFO order)
TopToBottom =>
334 for Int
i = MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1; Int
i (self_ : Int, other : Int) -> Bool
>= 0; Int
i = Int
i (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1 {
335 (T) -> Unit
f(MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
336 }
337 IterationOrder::IterationOrder
From bottom to top
BottomToTop =>
338 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
339 (T) -> Unit
f(MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
340 }
341 }
342}
343
344///|
345/// Convert the stack to an array
346///
347/// # Example
348/// ```
349/// let arr = stack.to_array(IterationOrder::TopToBottom)
350/// ```
351pub fn (self : MaxStack[T], order : IterationOrder) -> Array[T]
Convert the stack to an array
Example
let arr = stack.to_array(IterationOrder::TopToBottom)
to_array[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], IterationOrder
order : enum IterationOrder {
TopToBottom
BottomToTop
}
Stack iteration direction
IterationOrder) -> type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[type parameter T
T] {
352 let Array[T]
result = []
353 MaxStack[T]
self.(self : MaxStack[T], order : IterationOrder, f : (T) -> Unit) -> Unit
Iterate through elements in the stack
Example
stack.iter(IterationOrder::TopToBottom, fn(value) {
println("Element: \{value}")
})
iter(IterationOrder
order, fn(T
value) { Array[T]
result.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(T
value) })
354 Array[T]
result
355}
356
357///|
358/// Find the position of an element in the stack (counting from the top)
359///
360/// # Example
361/// ```
362/// match stack.find(42) {
363/// Some(index) => println("Found element at position \{index} from top")
364/// None => println("Element not found")
365/// }
366/// ```
367pub fn (self : MaxStack[T], target : T) -> Int?
Find the position of an element in the stack (counting from the top)
Example
match stack.find(42) {
Some(index) => println("Found element at position \{index} from top")
None => println("Element not found")
}
find[T : trait Eq {
op_equal(Self, Self) -> Bool
}
Trait for types whose elements can test for equality
Eq](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], T
target : type parameter T
T) -> Int
Int? {
368 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
369 let Int
stack_top_index = MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1 (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- Int
i
370 if MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[stack_top_index].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap() (_ : T, _ : T) -> Bool
== T
target {
371 return (Int) -> Int?
Some(Int
i)
372 }
373 }
374 Int?
None
375}
376
377///|
378/// Check if the stack contains a specific element
379///
380/// # Example
381/// ```
382/// if stack.contains(42) {
383/// println("Stack contains 42")
384/// }
385/// ```
386pub fn (self : MaxStack[T], target : T) -> Bool
Check if the stack contains a specific element
Example
if stack.contains(42) {
println("Stack contains 42")
}
contains[T : trait Eq {
op_equal(Self, Self) -> Bool
}
Trait for types whose elements can test for equality
Eq](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], T
target : type parameter T
T) -> Bool
Bool {
387 MaxStack[T]
self.(self : MaxStack[T], target : T) -> Int?
Find the position of an element in the stack (counting from the top)
Example
match stack.find(42) {
Some(index) => println("Found element at position \{index} from top")
None => println("Element not found")
}
find(T
target) (x : Int?, y : Int?) -> Bool
!= Int?
None
388}
389
390///|
391/// Create a snapshot of the stack
392///
393/// # Example
394/// ```
395/// let snapshot = stack.snapshot()
396/// println("Snapshot timestamp: \{snapshot.timestamp}")
397/// ```
398pub fn (self : MaxStack[T]) -> StackSnapshot[T]
Create a snapshot of the stack
Example
let snapshot = stack.snapshot()
println("Snapshot timestamp: \{snapshot.timestamp}")
snapshot[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> struct StackSnapshot[T] {
data_stack: Array[T]
max_stack: Array[T]
current_size: Int
current_max: T?
timestamp: Int
}
Stack snapshot (for debugging and analysis)
StackSnapshot[type parameter T
T] {
399 let Array[T]
data_copy = []
400 let Array[T]
max_copy = []
401 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
402 Array[T]
data_copy.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
403 Array[T]
max_copy.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
404 }
405 {
406 Array[T]
Current data stack contents
data_stack: Array[T]
data_copy,
407 Array[T]
Current max stack contents
max_stack: Array[T]
max_copy,
408 Int
Current size
current_size: MaxStack[T]
self.Int
Current stack size
size,
409 T?
Current maximum value
current_max: if MaxStack[T]
self.Int
Current stack size
size (self_ : Int, other : Int) -> Bool
> 0 {
410 (T) -> T?
Some(MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
411 } else {
412 T?
None
413 },
414 Int
Timestamp (identifies snapshot time)
timestamp: 0, // In actual implementation can use real timestamp
415 }
416}
417
418///|
419/// Serialize stack
420///
421/// # Example
422/// ```
423/// let serialized = stack.serialize()
424/// ```
425pub fn (self : MaxStack[T]) -> SerializedMaxStack[T]
Serialize stack
Example
let serialized = stack.serialize()
serialize[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> struct SerializedMaxStack[T] {
data: Array[T]
max_data: Array[T]
size: Int
capacity: Int
version: Int
}
Serialization format
SerializedMaxStack[type parameter T
T] {
426 let Array[T]
data_copy = []
427 let Array[T]
max_copy = []
428 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
429 Array[T]
data_copy.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
430 Array[T]
max_copy.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap())
431 }
432 {
433 Array[T]
Contents of data stack
data: Array[T]
data_copy,
434 Array[T]
Contents of max stack
max_data: Array[T]
max_copy,
435 Int
Stack size
size: MaxStack[T]
self.Int
Current stack size
size,
436 Int
Capacity
capacity: MaxStack[T]
self.(self : MaxStack[T]) -> Int
Get the capacity of the stack
Example
println("Stack capacity: \{stack.capacity()}")
capacity(),
437 Int
Version number
version: 1,
438 }
439}
440
441///|
442/// Deserialize stack
443///
444/// # Example
445/// ```
446/// let stack = @MaxStack.deserialize(serialized_data)!
447/// ```
448pub fn (data : SerializedMaxStack[T]) -> MaxStack[T] raise Error
Deserialize stack
Example
let stack = @MaxStack.deserialize(serialized_data)!
deserialize[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](SerializedMaxStack[T]
data : struct SerializedMaxStack[T] {
data: Array[T]
max_data: Array[T]
size: Int
capacity: Int
version: Int
}
Serialization format
SerializedMaxStack[type parameter T
T]) -> struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]! {
449 if SerializedMaxStack[T]
data.Int
Version number
version (x : Int, y : Int) -> Bool
!= 1 {
450 raise StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig("Unsupported version: \{SerializedMaxStack[T]
data.Int
Version number
version}")
451 }
452 if SerializedMaxStack[T]
data.Array[T]
Contents of data stack
data.(self : Array[T]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length() (x : Int, y : Int) -> Bool
!= SerializedMaxStack[T]
data.Array[T]
Contents of max stack
max_data.(self : Array[T]) -> Int
Returns the number of elements in the array.
Parameters:
array : The array whose length is to be determined.
Returns the number of elements in the array as an integer.
Example:
let arr = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : Array[Int] = []
inspect(empty.length(), content="0")
length() {
453 raise StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(
454 "Data and max_data arrays must have same length",
455 )
456 }
457 let MaxStackConfig
config = struct MaxStackConfig {
initial_capacity: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack configuration parameters
MaxStackConfig::{
458 Int
Initial capacity
initial_capacity: if SerializedMaxStack[T]
data.Int
Capacity
capacity (self_ : Int, other : Int) -> Bool
> 16 {
459 SerializedMaxStack[T]
data.Int
Capacity
capacity
460 } else {
461 16
462 },
463 Bool
Whether auto-resize is enabled
auto_resize: true,
464 Double
Growth factor (used when auto_resize is true)
growth_factor: 2.0,
465 }
466 let MaxStack[T]
stack = (config : MaxStackConfig) -> MaxStack[T] raise Error
Create a new MaxStack
Example
let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)
new!(MaxStackConfig
config)
467
468 // Restore data
469 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< SerializedMaxStack[T]
data.Int
Stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
470 MaxStack[T]
stack.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = (T) -> T?
Some(SerializedMaxStack[T]
data.Array[T]
Contents of data stack
data(Array[T], Int) -> T
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i])
471 MaxStack[T]
stack.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[i] = (T) -> T?
Some(SerializedMaxStack[T]
data.Array[T]
Contents of max stack
max_data(Array[T], Int) -> T
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i])
472 }
473 MaxStack[T]
stack.Int
Current stack size
size = SerializedMaxStack[T]
data.Int
Stack size
size
474 MaxStack[T]
stack
475}
476
477///|
478/// Compare if two stacks are equal
479///
480/// # Example
481/// ```
482/// if stack1.equals(stack2) {
483/// println("Stacks are equal")
484/// }
485/// ```
486pub fn (self : MaxStack[T], other : MaxStack[T]) -> Bool
Compare if two stacks are equal
Example
if stack1.equals(stack2) {
println("Stacks are equal")
}
equals[T : trait Eq {
op_equal(Self, Self) -> Bool
}
Trait for types whose elements can test for equality
Eq](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], MaxStack[T]
other : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> Bool
Bool {
487 if MaxStack[T]
self.Int
Current stack size
size (x : Int, y : Int) -> Bool
!= MaxStack[T]
other.Int
Current stack size
size {
488 return false
489 }
490 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
491 if MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap() (x : T, y : T) -> Bool
!= MaxStack[T]
other.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap() {
492 return false
493 }
494 }
495 true
496}
497
498///|
499/// Safe creation operation
500///
501/// # Example
502/// ```
503/// let config = MaxStackConfig::{ initial_capacity: 10, auto_resize: true, growth_factor: 2.0 }
504/// match @MaxStack.try_new(config) {
505/// Ok(stack) => println("Creation successful")
506/// Err(error) => println("Creation failed: \{error}")
507/// }
508/// ```
509pub fn (config : MaxStackConfig) -> Result[MaxStack[T], StackError]
Safe creation operation
Example
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}")
}
try_new[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](
510 MaxStackConfig
config : struct MaxStackConfig {
initial_capacity: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack configuration parameters
MaxStackConfig
511) -> enum Result[A, B] {
Err(B)
Ok(A)
}
Result[struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], type! StackError {
Underflow
Overflow
InvalidCapacity(Int)
InvalidConfig(String)
}
Stack error types
StackError] {
512 try {
513 let MaxStack[T]
stack = (config : MaxStackConfig) -> MaxStack[T] raise Error
Create a new MaxStack
Example
let config = MaxStackConfig::{
initial_capacity: 10,
auto_resize: true,
growth_factor: 2.0
}
let stack = @MaxStack.new(config)
new!(MaxStackConfig
config)
514 (MaxStack[T]) -> Result[MaxStack[T], StackError]
Ok(MaxStack[T]
stack)
515 } catch {
516 StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
cap) => (StackError) -> Result[MaxStack[T], StackError]
Err(StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
cap))
517 StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg) => (StackError) -> Result[MaxStack[T], StackError]
Err(StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg))
518 _ => (StackError) -> Result[MaxStack[T], StackError]
Err(StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig("Unknown error"))
519 }
520}
521
522///|
523/// Batch push with error handling
524///
525/// # Example
526/// ```
527/// let results = stack.push_all([1, 2, 3])
528/// ```
529pub fn (self : MaxStack[T], values : Array[T]) -> Array[Result[Unit, StackError]]
Batch push with error handling
Example
let results = stack.push_all([1, 2, 3])
push_all[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](
530 MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T],
531 Array[T]
values : type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[type parameter T
T]
532) -> type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[enum Result[A, B] {
Err(B)
Ok(A)
}
Result[Unit
Unit, type! StackError {
Underflow
Overflow
InvalidCapacity(Int)
InvalidConfig(String)
}
Stack error types
StackError]] {
533 let Array[Result[Unit, StackError]]
results = []
534 for T
value in Array[T]
values {
535 Array[Result[Unit, StackError]]
results.(self : Array[Result[Unit, StackError]], value : Result[Unit, StackError]) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.(self : MaxStack[T], value : T) -> Result[Unit, StackError]
Modified try_push function including Underflow handling
try_push(T
value))
536 }
537 Array[Result[Unit, StackError]]
results
538}
539
540///|
541/// Batch pop elements
542///
543/// # Example
544/// ```
545/// let popped_values = stack.pop_n(3)
546/// ```
547pub fn (self : MaxStack[T], n : Int) -> Array[T]
Batch pop elements
Example
let popped_values = stack.pop_n(3)
pop_n[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], Int
n : Int
Int) -> type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[type parameter T
T] {
548 let Array[T]
result = []
549 let mut Int
count = 0
550 while Int
count (self_ : Int, other : Int) -> Bool
< Int
n (Bool, Bool) -> Bool
&& MaxStack[T]
self.(self : MaxStack[T]) -> Bool
Check if the stack is empty
Example
if stack.is_empty() {
println("Stack is empty")
}
is_empty() (self : Bool, other : Bool) -> Bool
Compares two boolean values for equality.
Parameters:
self : The first boolean value to compare.
other : The second boolean value to compare.
Returns true if both boolean values are equal (either both true or both
false), false otherwise.
Example:
inspect(true == true, content="true")
inspect(false == true, content="false")
inspect(true == false, content="false")
inspect(false == false, content="true")
== false {
551 match MaxStack[T]
self.(self : MaxStack[T]) -> StackResult[T]
Pop an element from the stack
Example
match stack.pop() {
StackResult::Success(value) => println("Popped: \{value}")
StackResult::Empty => println("Stack is empty")
_ => {}
}
pop() {
552 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
value) => {
553 Array[T]
result.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(T
value)
554 Int
count (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+= 1
555 }
556 _ => break
557 }
558 }
559 Array[T]
result
560}
561
562///|
563/// Get the nth element in the stack (from top, 0-indexed)
564///
565/// # Example
566/// ```
567/// match stack.get_nth(2) {
568/// StackResult::Success(value) => println("3rd element: \{value}")
569/// StackResult::Empty => println("Stack empty or index out of bounds")
570/// _ => {}
571/// }
572/// ```
573pub fn (self : MaxStack[T], index : Int) -> StackResult[T]
Get the nth element in the stack (from top, 0-indexed)
Example
match stack.get_nth(2) {
StackResult::Success(value) => println("3rd element: \{value}")
StackResult::Empty => println("Stack empty or index out of bounds")
_ => {}
}
get_nth[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], Int
index : Int
Int) -> enum StackResult[T] {
Success(T)
Empty
Full
}
Stack operation result type
StackResult[type parameter T
T] {
574 if Int
index (self_ : Int, other : Int) -> Bool
< 0 (Bool, Bool) -> Bool
|| Int
index (self_ : Int, other : Int) -> Bool
>= MaxStack[T]
self.Int
Current stack size
size {
575 return StackResult::StackResult[T]
Stack is empty, operation failed
Empty
576 }
577 let Int
actual_index = MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1 (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- Int
index
578 let T
value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[actual_index].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
579 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
value)
580}
581
582///|
583/// Get the minimum value in the stack
584///
585/// # Example
586/// ```
587/// match stack.get_min() {
588/// StackResult::Success(min_val) => println("Minimum value: \{min_val}")
589/// StackResult::Empty => println("Stack is empty")
590/// _ => {}
591/// }
592/// ```
593pub fn (self : MaxStack[T]) -> StackResult[T]
Get the minimum value in the stack
Example
match stack.get_min() {
StackResult::Success(min_val) => println("Minimum value: \{min_val}")
StackResult::Empty => println("Stack is empty")
_ => {}
}
get_min[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum StackResult[T] {
Success(T)
Empty
Full
}
Stack operation result type
StackResult[type parameter T
T] {
594 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
595 return StackResult::StackResult[T]
Stack is empty, operation failed
Empty
596 }
597 let mut T
min_value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack[0].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
598 for Int
i = 1; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
599 let T
value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
600 if T
value (self_ : T, other : T) -> Bool
< T
min_value {
601 T
min_value = T
value
602 }
603 }
604 StackResult::(T) -> StackResult[T]
Operation succeeded, returns value
Success(T
min_value)
605}
606
607///|
608/// Count elements in stack that satisfy a condition
609///
610/// # Example
611/// ```
612/// let count = stack.count_if(fn(x) { x > 10 })
613/// println("Number of elements > 10: \{count}")
614/// ```
615pub fn (self : MaxStack[T], predicate : (T) -> Bool) -> Int
Count elements in stack that satisfy a condition
Example
let count = stack.count_if(fn(x) { x > 10 })
println("Number of elements > 10: \{count}")
count_if[T](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], (T) -> Bool
predicate : (type parameter T
T) -> Bool
Bool) -> Int
Int {
616 let mut Int
count = 0
617 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< MaxStack[T]
self.Int
Current stack size
size; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
618 if (T) -> Bool
predicate(MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[i].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()) {
619 Int
count (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+= 1
620 }
621 }
622 Int
count
623}
624
625///|
626/// Force pop element (throws exception on empty stack)
627///
628/// # Example
629/// ```
630/// try {
631/// let value = stack.force_pop()!
632/// println("Popped: \{value}")
633/// } catch {
634/// StackError::Underflow => println("Stack underflow")
635/// }
636/// ```
637pub fn (self : MaxStack[T]) -> T raise Error
Force pop element (throws exception on empty stack)
Example
try {
let value = stack.force_pop()!
println("Popped: \{value}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_pop[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> type parameter T
T! {
638 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
639 raise StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow
640 }
641 MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
-= 1
642 let T
value = MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
643
644 // Clear values at corresponding position
645 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = T?
None
646 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int, T?) -> Unit
Sets the element at the specified index in the array to a new value. The
original value at that index is overwritten.
Parameters:
array : The array to modify.
index : The position in the array where the value will be set.
value : The new value to assign at the specified index.
Throws an error if index is negative or greater than or equal to the length
of the array.
Example:
let arr = [1, 2, 3]
arr[1] = 42
inspect(arr, content="[1, 42, 3]")
[self.Int
Current stack size
size] = T?
None
647 T
value
648}
649
650///|
651/// Force get top element (throws exception on empty stack)
652///
653/// # Example
654/// ```
655/// try {
656/// let top = stack.force_peek()!
657/// println("Top: \{top}")
658/// } catch {
659/// StackError::Underflow => println("Stack underflow")
660/// }
661/// ```
662pub fn (self : MaxStack[T]) -> T raise Error
Force get top element (throws exception on empty stack)
Example
try {
let top = stack.force_peek()!
println("Top: \{top}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_peek[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> type parameter T
T! {
663 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
664 raise StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow
665 }
666 MaxStack[T]
self.Array[T?]
Data stack, stores actual elements
data_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
667}
668
669///|
670/// Force get current maximum (throws exception on empty stack)
671///
672/// # Example
673/// ```
674/// try {
675/// let max_val = stack.force_get_max()!
676/// println("Maximum value: \{max_val}")
677/// } catch {
678/// StackError::Underflow => println("Stack underflow")
679/// }
680/// ```
681pub fn (self : MaxStack[T]) -> T raise Error
Force get current maximum (throws exception on empty stack)
Example
try {
let max_val = stack.force_get_max()!
println("Maximum value: \{max_val}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_get_max[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> type parameter T
T! {
682 if MaxStack[T]
self.Int
Current stack size
size (self : Int, other : Int) -> Bool
Compares two integers for equality.
Parameters:
self : The first integer to compare.
other : The second integer to compare.
Returns true if both integers have the same value, false otherwise.
Example:
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
== 0 {
683 raise StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow
684 }
685 MaxStack[T]
self.Array[T?]
Max stack, stores the maximum value at each position
max_stack(Array[T?], Int) -> T?
Retrieves an element from the array at the specified index.
Parameters:
array : The array to get the element from.
index : The position in the array from which to retrieve the element.
Returns the element at the specified index.
Throws a panic if the index is negative or greater than or equal to the
length of the array.
Example:
let arr = [1, 2, 3]
inspect(arr[1], content="2")
[self.Int
Current stack size
size (self : Int, other : Int) -> Int
Performs subtraction between two 32-bit integers, following standard two's
complement arithmetic rules. When the result overflows or underflows, it
wraps around within the 32-bit integer range.
Parameters:
self : The minuend (the number being subtracted from).
other : The subtrahend (the number to subtract).
Returns the difference between self and other.
Example:
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
- 1].(self : T?) -> T
Extract the value in Some.
If the value is None, it throws a panic.
unwrap()
686}
687
688///|
689/// Batch pop elements (forced version)
690///
691/// # Example
692/// ```
693/// try {
694/// let popped = stack.force_pop_n(3)!
695/// println("Popped elements: \{popped}")
696/// } catch {
697/// StackError::Underflow => println("Not enough elements in stack")
698/// }
699/// ```
700pub fn (self : MaxStack[T], n : Int) -> Array[T] raise Error
Batch pop elements (forced version)
Example
try {
let popped = stack.force_pop_n(3)!
println("Popped elements: \{popped}")
} catch {
StackError::Underflow => println("Not enough elements in stack")
}
force_pop_n[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], Int
n : Int
Int) -> type Array[T]
An Array is a collection of values that supports random access and can
grow in size.
Array[type parameter T
T]! {
701 if Int
n (self_ : Int, other : Int) -> Bool
> MaxStack[T]
self.Int
Current stack size
size {
702 raise StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow
703 }
704 let Array[T]
result = []
705 for Int
i = 0; Int
i (self_ : Int, other : Int) -> Bool
< Int
n; Int
i = Int
i (self : Int, other : Int) -> Int
Adds two 32-bit signed integers. Performs two's complement arithmetic, which
means the operation will wrap around if the result exceeds the range of a
32-bit integer.
Parameters:
self : The first integer operand.
other : The second integer operand.
Returns a new integer that is the sum of the two operands. If the
mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to
2,147,483,647), the result wraps around according to two's complement rules.
Example:
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
+ 1 {
706 Array[T]
result.(self : Array[T], value : T) -> Unit
Adds an element to the end of the array.
If the array is at capacity, it will be reallocated.
Example
let v = []
v.push(3)
push(MaxStack[T]
self.(self : MaxStack[T]) -> T raise Error
Force pop element (throws exception on empty stack)
Example
try {
let value = stack.force_pop()!
println("Popped: \{value}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_pop!())
707 }
708 Array[T]
result
709}
710
711///|
712/// Safe forced pop operation
713///
714/// # Example
715/// ```
716/// match stack.try_force_pop() {
717/// Ok(value) => println("Popped: \{value}")
718/// Err(StackError::Underflow) => println("Stack is empty")
719/// Err(error) => println("Other error: \{error}")
720/// }
721/// ```
722pub fn (self : MaxStack[T]) -> Result[T, StackError]
Safe forced pop operation
Example
match stack.try_force_pop() {
Ok(value) => println("Popped: \{value}")
Err(StackError::Underflow) => println("Stack is empty")
Err(error) => println("Other error: \{error}")
}
try_force_pop[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T]) -> enum Result[A, B] {
Err(B)
Ok(A)
}
Result[type parameter T
T, type! StackError {
Underflow
Overflow
InvalidCapacity(Int)
InvalidConfig(String)
}
Stack error types
StackError] {
723 try {
724 let T
value = MaxStack[T]
self.(self : MaxStack[T]) -> T raise Error
Force pop element (throws exception on empty stack)
Example
try {
let value = stack.force_pop()!
println("Popped: \{value}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_pop!()
725 (T) -> Result[T, StackError]
Ok(T
value)
726 } catch {
727 StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow => (StackError) -> Result[T, StackError]
Err(StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow)
728 _ => (StackError) -> Result[T, StackError]
Err(StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig("Unknown error"))
729 }
730}
731
732///|
733/// Modified try_push function including Underflow handling
734pub fn (self : MaxStack[T], value : T) -> Result[Unit, StackError]
Modified try_push function including Underflow handling
try_push[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](
735 MaxStack[T]
self : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T],
736 T
value : type parameter T
T
737) -> enum Result[A, B] {
Err(B)
Ok(A)
}
Result[Unit
Unit, type! StackError {
Underflow
Overflow
InvalidCapacity(Int)
InvalidConfig(String)
}
Stack error types
StackError] {
738 try {
739 MaxStack[T]
self.(self : MaxStack[T], value : T) -> Unit raise Error
Push an element onto the stack
Example
let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!
push!(T
value)
740 (Unit) -> Result[Unit, StackError]
Ok(())
741 } catch {
742 StackError::StackError
Stack overflow (push operation on full stack)
Overflow => (StackError) -> Result[Unit, StackError]
Err(StackError::StackError
Stack overflow (push operation on full stack)
Overflow)
743 StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow => (StackError) -> Result[Unit, StackError]
Err(StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow)
744 StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
cap) => (StackError) -> Result[Unit, StackError]
Err(StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
cap))
745 StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg) => (StackError) -> Result[Unit, StackError]
Err(StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg))
746 _ => (StackError) -> Result[Unit, StackError]
Err(StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig("Unknown error"))
747 }
748}
749
750///|
751/// Modified safe_operations function including Underflow handling
752pub fn (stack : MaxStack[T], value : T) -> String
Modified safe_operations function including Underflow handling
safe_operations[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](MaxStack[T]
stack : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T], T
value : type parameter T
T) -> String
String {
753 try {
754 MaxStack[T]
stack.(self : MaxStack[T], value : T) -> Unit raise Error
Push an element onto the stack
Example
let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!
push!(T
value)
755 "Success"
756 } catch {
757 StackError::StackError
Stack overflow (push operation on full stack)
Overflow => "Stack overflow"
758 StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow => "Stack underflow"
759 StackError::(Int) -> StackError
Invalid capacity
InvalidCapacity(Int
cap) => "Invalid capacity: \{Int
cap}"
760 StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg) => "Config error: \{String
msg}"
761 _ => "Unknown error"
762 }
763}
764
765///|
766/// Modified selective_error_handling function including Underflow handling
767pub fn (stack : MaxStack[T], value : T) -> Unit raise Error
Modified selective_error_handling function including Underflow handling
selective_error_handling[T : trait Compare {
compare(Self, Self) -> Int
}
Trait for types whose elements are ordered
The return value of [compare] is:
- zero, if the two arguments are equal
- negative, if the first argument is smaller
- positive, if the first argument is greater
Compare](
768 MaxStack[T]
stack : struct MaxStack[T] {
mut data_stack: Array[T?]
mut max_stack: Array[T?]
mut size: Int
auto_resize: Bool
growth_factor: Double
}
MaxStack dual-stack implementation
Uses two stacks: one for data storage, one for tracking max values at each position
MaxStack[type parameter T
T],
769 T
value : type parameter T
T
770) -> Unit
Unit! {
771 try {
772 MaxStack[T]
stack.(self : MaxStack[T], value : T) -> Unit raise Error
Push an element onto the stack
Example
let stack = @MaxStack.default()
stack.push(42)!
stack.push(24)!
push!(T
value)
773 (t : T) -> Unit
Evaluates an expression and discards its result. This is useful when you want
to execute an expression for its side effects but don't care about its return
value, or when you want to explicitly indicate that a value is intentionally
unused.
Parameters:
value : The value to be ignored. Can be of any type.
Example:
let x = 42
ignore(x) // Explicitly ignore the value
let mut sum = 0
ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
ignore(MaxStack[T]
stack.(self : MaxStack[T]) -> T raise Error
Force pop element (throws exception on empty stack)
Example
try {
let value = stack.force_pop()!
println("Popped: \{value}")
} catch {
StackError::Underflow => println("Stack underflow")
}
force_pop!())
774 } catch! {
775 StackError::(String) -> StackError
Invalid configuration parameter
InvalidConfig(String
msg) =>
776 (input : String) -> Unit
Prints any value that implements the Show trait to the standard output,
followed by a newline.
Parameters:
value : The value to be printed. Must implement the Show trait.
Example:
println(42)
println("Hello, World!")
println([1, 2, 3])
println("Configuration error handled: \{String
msg}")
777 StackError::StackError
Stack underflow (pop operation on empty stack)
Underflow => (input : String) -> Unit
Prints any value that implements the Show trait to the standard output,
followed by a newline.
Parameters:
value : The value to be printed. Must implement the Show trait.
Example:
println(42)
println("Hello, World!")
println([1, 2, 3])
println("Underflow error handled")
778 // Other errors will be rethrown
779 }
780}
781