Files
kraken/stdlib/set.krak
Nathan Braswell 1f119af8ad more work
2015-08-06 02:42:40 -04:00

85 lines
1.9 KiB
Plaintext

import vector
import io
fun set<T>(): set<T> {
var toRet.construct() : set<T>
return toRet
}
fun set<T>(item: T): set<T> {
var toRet.construct() : set<T>
toRet.add(item)
return toRet
}
fun from_vector<T>(items: vector::vector<T>): set<T> {
var toRet.construct() : set<T>
items.for_each( fun(item: T) toRet.add(item); )
return toRet
}
obj set<T> (Object) {
var data: vector::vector<T>
fun construct() {
data.construct()
}
fun copy_construct(old: *set<T>) {
data.copy_construct(&old->data)
}
fun operator=(rhs: set<T>) {
destruct()
copy_construct(&rhs)
}
fun operator==(rhs: set<T>): bool {
if (size() != rhs.size())
return false
return !data.any_true( fun(item: T): bool return !rhs.contains(item); )
}
fun operator!=(rhs: set<T>): bool {
return ! (*this == rhs)
}
fun destruct() {
data.destruct()
}
fun size():int {
return data.size
}
fun contains(items: set<T>): bool {
return items.size() == 0 || !items.any_true( fun(item: T): bool return !contains(item); )
}
fun contains(item: T): bool {
return data.find(item) != -1
}
fun operator+=(item: T) {
add(item)
}
fun operator+=(items: set<T>) {
add(items)
}
fun add(item: ref T) {
if (!contains(item))
data.add(item)
}
fun add(items: ref set<T>) {
items.for_each( fun(item: ref T) add(item); )
}
fun remove(item: T) {
var idx = data.find(item)
if (idx == -1) {
io::println("CANNOT FIND ITEM TO REMOVE")
return
}
data.remove(idx)
}
fun for_each(func: fun(ref T):void) {
data.for_each(func)
}
fun for_each(func: fun(T):void) {
data.for_each(func)
}
fun any_true(func: fun(T):bool):bool {
return data.any_true(func)
}
}