refactoring into a functor parameterized on tree dimensionality and distance function