56 lines
1.4 KiB
Plaintext
56 lines
1.4 KiB
Plaintext
ns std::collections
|
|
|
|
use std::collections::Collection
|
|
|
|
pub int Stack<T> : Collection<T> {
|
|
fn push(element: T)
|
|
fn pop(): Option<T>
|
|
fn get_at(index: Int): Option<T>
|
|
}
|
|
|
|
pub impl ArrayStack<T : Default | Empty> : Stack<T> {
|
|
fld arr: mut Array<T> = array::of_length(16, std::reflect::default_or_empty<T>)
|
|
fld current_index: mut Int = 0
|
|
|
|
impl fn <U> map(m) {
|
|
let result: mut Array<U> = array::of_length(arr.length, std::reflect::default_or_empty<U>)
|
|
for (element, i) in arr.iter_with_indices() {
|
|
result[i] = m(element)
|
|
}
|
|
result
|
|
}
|
|
|
|
impl fn <U> flat_map(m) {
|
|
let result: mut Array<U> = array::of_length(arr.length, std::reflect::default_or_empty<Array<U>>)
|
|
for (element, i) in arr.iter_with_indices() {
|
|
result[i] = m(element)
|
|
}
|
|
array::flatten(result)
|
|
}
|
|
|
|
impl fn get_size() = current_index
|
|
|
|
impl fn push(element) {
|
|
if current_index == arr.length {
|
|
arr = array::clone(size = arr.length * 2, source = arr)
|
|
}
|
|
arr[current_index] = element
|
|
current_index++
|
|
}
|
|
|
|
impl fn pop() {
|
|
if current_index > 0 {
|
|
let element = arr[current_index - 1]
|
|
current_index--
|
|
return Some(element)
|
|
}
|
|
None
|
|
}
|
|
|
|
impl fn get_at(index) = index < arr.length ? Some(arr[index]) : None
|
|
}
|
|
|
|
pub mod stack {
|
|
pub fn of<T : PartialEq>(items: ...T): List<T> = ArrayList(items)
|
|
}
|