Exemple #1
0
 static <T> Stream<T> inOrder(Tree<T> tree) {
   if (tree.isLeaf()) {
     return Stream.of(tree.getValue());
   } else {
     final List<Node<T>> children = tree.getChildren();
     return children
         .tail()
         .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(inOrder(child)))
         .prepend(tree.getValue())
         .prependAll(inOrder(children.head()));
   }
 }
Exemple #2
0
 private static String toLispString(Tree<?> tree) {
   final String value = String.valueOf(tree.getValue());
   if (tree.isLeaf()) {
     return value;
   } else {
     return String.format(
         "(%s %s)", value, tree.getChildren().map(Node::toLispString).mkString(" "));
   }
 }
Exemple #3
0
 static <T> Stream<T> levelOrder(Tree<T> tree) {
   Stream<T> result = Stream.empty();
   final java.util.Queue<Tree<T>> queue = new java.util.LinkedList<>();
   queue.add(tree);
   while (!queue.isEmpty()) {
     final Tree<T> next = queue.remove();
     result = result.prepend(next.getValue());
     queue.addAll(next.getChildren().toJavaList());
   }
   return result.reverse();
 }
Exemple #4
0
 @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()));
   }
 }
Exemple #5
0
 static <T> Stream<T> postOrder(Tree<T> tree) {
   return tree.getChildren()
       .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(postOrder(child)))
       .append(tree.getValue());
 }
Exemple #6
0
 static <T> Stream<T> preOrder(Tree<T> tree) {
   return tree.getChildren()
       .foldLeft(Stream.of(tree.getValue()), (acc, child) -> acc.appendAll(preOrder(child)));
 }