73 lines
2.1 KiB
Plaintext
73 lines
2.1 KiB
Plaintext
import mem
|
|
import vec
|
|
import io:*
|
|
import str:*
|
|
|
|
obj tree<T> (Object) {
|
|
var data: T
|
|
var parent: *tree<T>
|
|
var children: vec::vec<*tree<T>>
|
|
fun construct(dataIn: ref T): *tree<T> {
|
|
mem::maybe_copy_construct(&data, &dataIn)
|
|
parent = mem::null<tree<T>>()
|
|
children.construct()
|
|
return this
|
|
}
|
|
fun construct(dataIn: ref T, c: ref vec::vec<*tree<T>>): *tree<T> {
|
|
mem::maybe_copy_construct(&data, &dataIn)
|
|
parent = mem::null<tree<T>>()
|
|
children.copy_construct(&c)
|
|
children.for_each(fun(i: *tree<T>) {
|
|
i->parent = this
|
|
})
|
|
return this
|
|
}
|
|
// Some of these don't really make much sense considering this tree is all about
|
|
// heap allocated pointers. Best to have it for saftey, though
|
|
fun copy_construct(old: *tree<T>) {
|
|
mem::maybe_copy_construct(&data, &old->data)
|
|
parent = old->parent
|
|
children.copy_construct(&old->children)
|
|
}
|
|
// ditto
|
|
fun operator=(other: tree<T>):void {
|
|
destruct()
|
|
copy_construct(&other)
|
|
}
|
|
fun operator==<U>(other: ref tree<U>):bool {
|
|
return data == other.data
|
|
}
|
|
fun destruct() {
|
|
mem::maybe_destruct(&data)
|
|
children.destruct()
|
|
}
|
|
fun add_child(c: *tree<T>) {
|
|
children.add(c)
|
|
c->parent = this
|
|
}
|
|
fun add_children(c: vec::vec<*tree<T>>) {
|
|
for (var i = 0; i < c.size; i++;) {
|
|
children.add(c[i])
|
|
c[i]->parent = this
|
|
}
|
|
}
|
|
fun set_child(i: int, c: *tree<T>) {
|
|
children[i] = c
|
|
c->parent = this
|
|
}
|
|
fun replace_child(old_c: *tree<T>, new_c: *tree<T>) {
|
|
children[children.find(old_c)] = new_c
|
|
new_c->parent = this
|
|
}
|
|
fun remove_child(old_c: *tree<T>) {
|
|
children.remove(children.find(old_c))
|
|
}
|
|
fun clone(): *tree<T> {
|
|
return mem::new<tree<T>>()->construct(data, children.map(fun(c: *tree<T>): *tree<T> return c->clone();))
|
|
}
|
|
fun clone(f: fun(ref T): T): *tree<T> {
|
|
return mem::new<tree<T>>()->construct(f(data), children.map(fun(c: *tree<T>): *tree<T> return c->clone(f);))
|
|
}
|
|
}
|
|
|