Example #1
0
 /**
  * Provides a stream of the elements of the tree at each level, in level order.
  *
  * @return The elements of the tree at each level.
  */
 public Stream<Stream<A>> levels() {
   final F<Stream<Tree<A>>, Stream<Tree<A>>> flatSubForests =
       Stream.<Tree<A>, Tree<A>>bind_()
           .f(compose(P1.<Stream<Tree<A>>>__1(), Tree.<A>subForest_()));
   final F<Stream<Tree<A>>, Stream<A>> roots = Stream.<Tree<A>, A>map_().f(Tree.<A>root_());
   return iterateWhile(flatSubForests, Stream.<Tree<A>>isNotEmpty_(), single(this)).map(roots);
 }
Example #2
0
 private static <A> Stream<String> drawSubTrees(final Show<A> s, final Stream<Tree<A>> ts) {
   return ts.isEmpty()
       ? Stream.nil()
       : ts.tail()._1().isEmpty()
           ? shift("`- ", "   ", ts.head().drawTree(s)).cons("|")
           : shift("+- ", "|  ", ts.head().drawTree(s)).append(drawSubTrees(s, ts.tail()._1()));
 }
Example #3
0
 /**
  * Puts the elements of the tree into a Stream, in pre-order.
  *
  * @return The elements of the tree in pre-order.
  */
 public Stream<A> flatten() {
   final F2<Tree<A>, P1<Stream<A>>, Stream<A>> squish =
       new F2<Tree<A>, P1<Stream<A>>, Stream<A>>() {
         public Stream<A> f(final Tree<A> t, final P1<Stream<A>> xs) {
           return cons(
               t.root(),
               t.subForest().map(Stream.<Tree<A>, Stream<A>>foldRight().f(curry()).f(xs._1())));
         }
       };
   return squish.f(this, P.p(Stream.<A>nil()));
 }
Example #4
0
 /**
  * Creates a nullary tree.
  *
  * @param root The root element of the tree.
  * @return A nullary tree with the root element in it.
  */
 public static <A> Tree<A> leaf(final A root) {
   return node(root, Stream.nil());
 }
Example #5
0
 /**
  * Builds a tree from a seed value.
  *
  * @param f A function with which to build the tree.
  * @return A function which, given a seed value, yields a tree.
  */
 public static <A, B> F<B, Tree<A>> unfoldTree(final F<B, P2<A, P1<Stream<B>>>> f) {
   return b -> {
     final P2<A, P1<Stream<B>>> p = f.f(b);
     return node(p._1(), p._2().map(Stream.<B, Tree<A>>map_().f(unfoldTree(f))));
   };
 }
Example #6
0
 /**
  * Maps the given function over this tree.
  *
  * @param f The function to map over this tree.
  * @return The new Tree after the function has been applied to each element in this Tree.
  */
 public <B> Tree<B> fmap(final F<A, B> f) {
   return node(
       f.f(root()), subForest().map(Stream.<Tree<A>, Tree<B>>map_().f(Tree.<A, B>fmap_().f(f))));
 }
Example #7
0
 private static Stream<String> shift(final String f, final String o, final Stream<String> s) {
   return Stream.repeat(o).cons(f).zipWith(s, Monoid.stringMonoid.sum());
 }