@SuppressWarnings("unchecked") static <T, U> Tree<U> apply( Node<T> node, Function<? super T, ? extends Iterable<? extends U>> mapper) { final Tree<U> mapped = Tree.ofAll(mapper.apply(node.getValue())); if (mapped.isEmpty()) { return Tree.empty(); } else { final List<Node<U>> children = (List<Node<U>>) (Object) node.getChildren() .map(child -> FlatMap.apply(child, mapper)) .filter(Tree::isDefined); return Tree.of(mapped.getValue(), children.prependAll(mapped.getChildren())); } }
@Override default Tree<T> clear() { return Tree.empty(); }
/** * Returns a Tree containing {@code n} values supplied by a given Supplier {@code s}. * * @param <T> Component type of the Tree * @param n The number of elements in the Tree * @param s The Supplier computing element values * @return A Tree of size {@code n}, where each element contains the result supplied by {@code s}. * @throws NullPointerException if {@code s} is null */ static <T> Tree<T> fill(int n, Supplier<? extends T> s) { Objects.requireNonNull(s, "s is null"); return Collections.fill(n, s, Tree.empty(), Tree::of); }
/** * Returns a Tree containing {@code n} values of a given Function {@code f} over a range of * integer values from 0 to {@code n - 1}. * * @param <T> Component type of the Tree * @param n The number of elements in the Tree * @param f The Function computing element values * @return A Tree consisting of elements {@code f(0),f(1), ..., f(n - 1)} * @throws NullPointerException if {@code f} is null */ static <T> Tree<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); return Collections.tabulate(n, f, Tree.empty(), Tree::of); }