public static <A> void printTree(Tree<A> tree, PrintStream ps) { ps.printf("(%s (", tree.value()); for (Tree<A> t : tree.children()) { printTree(t, ps); ps.print(","); } ps.print("))"); }
// TODO all this is very memory inefficient and will lead to stack overflows for very deep trees public static ObjectNode toJsonTree(ObjectMapper objectMapper, Tree<? extends JsonNode> tree) { final ObjectNode node = objectMapper.createObjectNode(); node.put("_value", tree.value()); final ArrayNode children = objectMapper.createArrayNode(); for (Tree<? extends JsonNode> child : tree.children()) children.add(toJsonTree(objectMapper, child)); node.put("_children", children); return node; }
/** * Map a function over a tree * * @param fn Function * @param tree Tree of {@code A}'s * @return Tree of {@code B}'s */ public static <A,B> Tree<B> map(final Function<A,B> fn, Tree<A> tree) { final B value = fn.apply(tree.value()); if (isLeaf(tree)) return new ImmutableTree<B>(value); else { final Function<Tree<A>,Tree<B>> tmap = new Function<Tree<A>,Tree<B>>() { public Tree<B> apply(Tree<A> tree) { return map(fn, tree); } }; final Iterable<Tree<B>> tb = Iterables.transform(tree.children(), tmap); return new ImmutableTree<B>(value, tb); } }
public static final <_> boolean isLeaf(final Tree<_> tree) { return Iterables.isEmpty(tree.children()); }