Scala-fy a java function? -
i've switched assignment java scala. however, still looks java. example, function below search on range tree, , inside there "isinstanceof" checks.
however - replacing them "match" seems take more space. can suggest improvements on how "scalify" code?
def rangesearch2d(treeroot: node, lower: data2d, upper: data2d, visited: visited): seq[data2d] = { if (treeroot == null) { // return empty list return vector() } // increment visit count if (visited != null) visited.visit2d(treeroot) var results = arraybuffer[data2d]() // find nearest common ancestor value between lower.x , upper.x var common: node = commonancestor(treeroot, lower, upper, visited) if (common.isinstanceof[leafnode]) { return vector(common.asinstanceof[leafnode].data) } /** common non-leaf node, must process subtree */ /** process left subtree */ var current = common.left while (!current.isinstanceof[leafnode]) { if (visited != null) visited.visit2d(current) //find path current lower.x if (lower.x <= current.midrange) { results.appendall(rangesearch1d(current.right.subtree, lower, upper, visited)) current = current.left } else { current = current.right } } //check if current leaf node in range if (inrange(current, lower, upper)) { results.append(current.asinstanceof[leafnode].data) } /** process right subtree */ current = common.right while (!current.isinstanceof[leafnode]) { if (visited != null) visited.visit2d(current) //find path current upper.x if (upper.x >= current.midrange) { results.appendall(rangesearch1d(current.left.subtree, lower, upper, visited)) current = current.right } else { current = current.left } } //check if current leaf node in range if (inrange(current, lower, upper)) { results.append(current.asinstanceof[leafnode].data) } return results }
well, first can rid of null
, replacing parameters might null
option
. in code, change
if (visited != null) visited.visit2d(x)
with
visited foreach (_ visit2d x)
both while loops can replaced recursive functions. instead of adding result mutable variable, can pass immutable accumulator parameter in recursive function.
if node
has extractor, use case guard make midrange
test. doesn't add much, more idiomatic.
i feeling both while loops can subsumed single recursion, haven't considered algorithm enough decided that. if so, away common
return.
by way, there's bug there, since there might not common ancestor within range.
Comments
Post a Comment