Can I improve this tree mutator ?

13 views
Skip to first unread message

Dimitar Georgiev

unread,
Jun 27, 2017, 11:37:04 AM6/27/17
to Functional Java
I've a function in my project that looks like this:

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
  


Tony Morris

unread,
Jun 27, 2017, 5:53:09 PM6/27/17
to functio...@googlegroups.com

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.

signature.asc

Dimitar Georgiev

unread,
Jun 29, 2017, 6:24:23 AM6/29/17
to Functional Java
Thanks! I considered, and tried that, and failed miserably since I have no experience working with zippers, and could not find any examples, at least for fj. I'll give it anoher shot.
Reply all
Reply to author
Forward
0 new messages