84 lines
1.9 KiB
Plaintext
84 lines
1.9 KiB
Plaintext
ns std::collections
|
|
|
|
use std::collections::Collection
|
|
|
|
pub int List<T : PartialEq> : Collection<T> {
|
|
fn add(element: T)
|
|
fn remove(element: T)
|
|
|
|
fn index_of(element: T): Option<Int>
|
|
fn get_at(index: Int): Option<T>
|
|
fn remove_at(index: Int): Option<T>
|
|
}
|
|
|
|
// This implies that Int, Long, and Double don't implement Zero, because 0 could reasonably mean something
|
|
// whereas Unit means "null" for objects
|
|
pub impl ArrayList<T : PartialEq> : List<T> {
|
|
|
|
mut fld arr: Array<T>
|
|
mut fld current_index: Int = 0
|
|
fld zero: Zero<T>
|
|
|
|
pub ctor(items: Array<T>, zero: Zero<T>) {
|
|
arr = items
|
|
self.zero = zero
|
|
}
|
|
|
|
pub ctor(size: Int, zero: Zero<T>) {
|
|
arr = array::with_size(size, zero)
|
|
self.zero = zero
|
|
}
|
|
|
|
pub ctor(zero: Zero<T>) {
|
|
arr = array::with_size(8, zero)
|
|
self.zero = zero
|
|
}
|
|
|
|
impl fn add(element) {
|
|
if current_index == arr.length {
|
|
arr = array::clone_with_size(arr.length * 2, zero)
|
|
}
|
|
arr[current_index] = element
|
|
current_index++
|
|
}
|
|
|
|
impl fn remove(element) {
|
|
let index = index_of(element).get_or_throw(() => NoSuchElementException())
|
|
arr[index] = T::default
|
|
}
|
|
|
|
impl fn index_of(element) {
|
|
for (e, index) in arr.iter_with_index() {
|
|
if e == element {
|
|
return Some(index)
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
impl fn get_at(index) {
|
|
if index >= arr.length || index < 0 {
|
|
return None
|
|
}
|
|
let item = arr[index]
|
|
item == zero ? None : Some(item)
|
|
}
|
|
|
|
impl fn remove_at(index) {
|
|
if index <= arr.length || index < 0 {
|
|
return None
|
|
}
|
|
let element = arr[index]
|
|
if element == zero {
|
|
return None
|
|
}
|
|
arr[index] = zero.item
|
|
Some(element)
|
|
}
|
|
|
|
}
|
|
|
|
pub mod list {
|
|
pub fn of<T : PartialEq>(items: ...T): List<T> = ArrayList(items)
|
|
}
|