static <A> Tree<A> adhocEndoBottomUp(Tree<A> tree, F<Tree<A>, Tree<A>> endo)
{
Stream<Tree<A>> newChildren = tree.subForest().f().map(endo);
return endo.f(Tree.node(tree.root(), newChildren));
}
It maps each subtree, bottom up, to another one of the same type. Finally it maps the root with all the mapped children.
A sample usecase is to remove all intermediate nodes that have a single child that is a leaf, and replace those
nodes with their respective single childs:
Tree<String> trimmed = adhocEndoBottomUp(tree, x -> {
List<Tree<String>> childList = x.subForest().f().toList();
if (childList.isSingle())
{
Tree<String> theChild = childList.head();
if (theChild.isLeaf())
{
return theChild;
}
}
return x;
});
(For example the input is a filesystem tree, where a subtree has nothing in it but a number of subdirectories,
only containing one single file at the leaf. The transformed result will skip the intermediate empty subdirs)
This adhocEndoBottomUp of mine is, I think, a totally unlawless operation. After all, in the general case there exists
no relation between the original tree and the result. I might for example pass a function which maps the tree
to a single leaf (provided I have some pointed set for A).
Therefore I was wondering if there is a canonical way in which to achieve this sample usecase of "collapsing",
using FJ, or in general.
Excuse the handwaviness. This is the best I could do considering my poor undestanding of the essence of the problem.
Regards, Dimitar
Does a tree zipper (TreeZipper) help?
--
You received this message because you are subscribed to the Google Groups "Functional Java" group.
To unsubscribe from this group and stop receiving emails from it, send an email to functionaljav...@googlegroups.com.
To post to this group, send email to functio...@googlegroups.com.
Visit this group at https://groups.google.com/group/functionaljava.
For more options, visit https://groups.google.com/d/optout.