How can I make this method more scalalicious

I have a function that calculates the left and right node values ​​for some treeNodes collection, given the simple association of node.id, node.parentId. It is very simple and works quite well ... but, well, I wonder if there is a more idiomatic approach. In particular, there is a way to track values ​​left / right without using any external tracked value, but at the same time maintain a delicious recursion.

/* 
 * A tree node
 */
case class TreeNode(val id:String, val parentId: String){
    var left: Int = 0
    var right: Int = 0
}

/* 
 * a method to compute the left/right node values 
 */
def walktree(node: TreeNode) = {
    /* 
     * increment state for the inner function 
     */
    var c = 0

    /*
     * A method to set the increment state
     */
    def increment = { c+=1; c } // poo

    /* 
     * the tasty inner method
     * treeNodes is a List[TreeNode]
     */
    def walk(node: TreeNode): Unit = {
      node.left = increment

      /* 
       * recurse on all direct descendants 
       */
      treeNodes filter( _.parentId == node.id) foreach (walk(_))

      node.right = increment
    }

    walk(node)
}

walktree(someRootNode)

Edit - The list of nodes is taken from the database. Pulling nodes into the correct tree will take too much time. I retrieve a flat list in memory, and all I have is an association via node id related to parents and children.

/ node ( ) SQL-.

, , - ( ).

Scala , /- . node. @dhg, . groupBy ( ?) , !

val treeNodeMap = treeNodes.groupBy(_.parentId).withDefaultValue(Nil)

def walktree(node: TreeNode) = {
    def walk(node: TreeNode, counter: Int): Int = {
        node.left = counter 
        node.right = 
          treeNodeMap(node.id) 
          .foldLeft(counter+1) {
            (result, curnode) => walk(curnode, result) + 1
        }
        node.right
    }
    walk(node,1)
}
+3
2

, -, .

, fold, . , treeNodes.groupBy(_.parentId) walktree, treeNodes.filter(...) walk.

val treeNodes = List(TreeNode("1","0"),TreeNode("2","1"),TreeNode("3","1"))

val treeNodeMap = treeNodes.groupBy(_.parentId).withDefaultValue(Nil)

def walktree2(node: TreeNode) = {
  def walk(node: TreeNode, c: Int): Int = {
    node.left = c
    val newC = 
      treeNodeMap(node.id)         // get the children without filtering
        .foldLeft(c+1)((c, child) => walk(child, c) + 1)
    node.right = newC
    newC
  }

  walk(node, 1)
}

:

scala> walktree2(TreeNode("0","-1"))
scala> treeNodes.map(n => "(%s,%s)".format(n.left,n.right))
res32: List[String] = List((2,7), (3,4), (5,6))

, :

case class TreeNode(        // class is now immutable; `walktree` returns a new tree
  id: String,
  value: Int,               // value to be set during `walktree` 
  left: Option[TreeNode],   // recursively-defined structure
  right: Option[TreeNode])  //   makes traversal much simpler

def walktree(node: TreeNode) = {
  def walk(nodeOption: Option[TreeNode], c: Int): (Option[TreeNode], Int) = {
    nodeOption match {
      case None => (None, c)  // if this child doesn't exist, do nothing
      case Some(node) =>      // if this child exists, recursively walk
        val (newLeft, cLeft) = walk(node.left, c)        // walk the left side
        val newC = cLeft + 1                             // update the value
        val (newRight, cRight) = walk(node.right, newC)  // walk the right side
        (Some(TreeNode(node.id, newC, newLeft, newRight)), cRight)
    }
  }

  walk(Some(node), 0)._1
}

:

walktree(
  TreeNode("1", -1,
    Some(TreeNode("2", -1,
      Some(TreeNode("3", -1, None, None)),
      Some(TreeNode("4", -1, None, None)))),
    Some(TreeNode("5", -1, None, None))))

:

Some(TreeNode(1,4,
  Some(TreeNode(2,2,
    Some(TreeNode(3,1,None,None)),
    Some(TreeNode(4,3,None,None)))),
  Some(TreeNode(5,5,None,None))))
+6

:

def walktree(node: TreeNode, c: Int): Int = {
    node.left = c

    val c2 = treeNodes.filter(_.parentId == node.id).foldLeft(c + 1) { 
        (cur, n) => walktree(n, cur)
    }

    node.right = c2 + 1
    c2 + 2
}

walktree(new TreeNode("", ""), 0)

, " ".

( http://codereview.stackexchange.com):

  • ... , TreeNode:

  • val case:

    case class TreeNode(val id: String, val parentId: String) {
    
  • = Unit Unit :

    def walktree(node: TreeNode) = {
    def walk(node: TreeNode): Unit = {
    
  • ():

    def increment = {c += 1; c}
    
  • , node:

    treeNodes filter (_.parentId == node.id) foreach (walk(_))
    
  • treeNodes foreach walk:

    treeNodes foreach (walk(_))
    
+1

All Articles