Files
kraken/stdlib/set.krak

117 lines
2.9 KiB
Plaintext

import vector
import io
import serialize
import util
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, Serializable) {
var data: vector::vector<T>
fun construct(): *set<T> {
data.construct()
return this
}
fun construct(ammt: int): *set<T> {
data.construct(ammt)
return this
}
fun copy_construct(old: *set<T>) {
data.copy_construct(&old->data)
}
fun operator=(rhs: set<T>) {
destruct()
copy_construct(&rhs)
}
fun serialize(): vector::vector<char> {
return serialize::serialize(data)
}
fun unserialize(it: ref vector::vector<char>, pos: int): int {
/*construct()*/
/*util::unpack(data, pos) = serialize::unserialize<vector::vector<T>>(it, pos)*/
return data.unserialize(it, pos)
}
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_all(items: ref set<T>) {
add(items)
}
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)
}
fun reduce<U>(func: fun(T,U): U, initial: U): U {
return data.reduce(func, initial)
}
fun flatten_map<U>(func: fun(T):set<U>):set<U> {
var newSet.construct(size()): set<U>
for (var i = 0; i < size(); i++;)
func(data[i]).for_each(fun(item: ref U) newSet.add(item);)
return newSet
}
fun filter(func: fun(T):bool):set<T> {
var newSet.construct(): set<T>
newSet.data = data.filter(func)
return newSet
}
}