convex.core.util.Trees Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of convex-core Show documentation
Show all versions of convex-core Show documentation
Convex core libraries and common utilities
The newest version!
package convex.core.util;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Utility class for tree handling functions
*/
public class Trees {
/**
* Visits elements on a stack, popping one off from the end each time.
* Visitor function MAY edit the stack. Will terminate when stack is empty.
*
* IMPORTANT: O(1) usage of JVM stack, may be necessary to use a function like this when
* visiting deeply nested trees in CVM code.
*
* @param Type of element to visit
* @param stack Stack of values to visit, must be a mutable List
* @param visitor Visitor function to call for each stack element.
*/
public static void visitStack(List stack, Consumer super T> visitor) {
while(!stack.isEmpty()) {
int pos=stack.size()-1;
T r=stack.remove(pos);
visitor.accept(r);
}
}
/**
* Visits elements on a stack, the element if predicate returns true.
* Predicate function MAY add to the stack. Will terminate when stack is empty.
*
* IMPORTANT: O(1) usage of JVM stack, may be necessary to use a function like this when
* visiting deeply nested trees in CVM code.
*
* @param Type of element to visit
* @param stack Stack of values to visit, must be a mutable List
* @param visitor Visitor function to call for each stack element.
*/
public static void visitStackMaybePopping(List stack, Predicate super T> visitor) {
while(!stack.isEmpty()) {
int pos=stack.size()-1;
T r=stack.get(pos);
boolean pop= visitor.test(r);
if (pop) stack.remove(pos);
}
}
}