I port the algorithm from Java to Scala, which does a range search on the VP Tree . Briefly, nodes in a tree have coordinates in space and a radius: nodes in this radius can be found in the left subtree, while nodes outside this radius are found in the right subtree. A range search tries to find all the objects in the tree at a given distance from the query object.
In Java, I passed an arraylist function in which it accumulated results, possibly recursing down one of both or both subtrees. Here's the direct port to Scala:
def search(node: VPNode[TPoint, TObject], query: TPoint, radius: Double, results: collection.mutable.Set[TObject]) { var dist = distance(query, node.point) if (dist < radius) results += node.obj if (node.left != null && dist <= radius + node.radius) search(node.left, query, radius, results) if (node.right != null && dist >= radius + node.radius) search(node.right, query, radius, results) }
Scala Collection types are immutable by default, and I thought it was a little annoying to introduce collection.mutable. all the time, so I started to study it. It seems recommended that using immutable collections is almost always wonderful: I use this code to execute millions of queries, although it seems to me that copying and concatenating an array of results will slow it down.
Answers such as this , for example, suggest that the problem needs to be approached more โfunctionallyโ.
So what should I do to solve this problem in a more Scala network? Ideally, I would like it to be as fast as the Java version, but I'm interested in the solutions independently (and can always project them to see if it matters).
Note that I was just starting to learn Scala (maybe I could cut my teeth for something useful), but I'm not new to functional programming, I used Haskell before (although I don't think I'm good at that!).