我有一个函数,在给定一个简单的node.id,node.parentId关联的情况下,计算某些treeNodes集合的左右节点值.这很简单,效果很好......但是,我想知道是否有更惯用的方法.具体来说,有一种方法可以跟踪左/右值而不使用一些外部跟踪值,但仍保持美味递归.
/*
* 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
* …Run Code Online (Sandbox Code Playgroud) 我正在尝试Scala 2.9(我喜欢它!)请考虑以下事项:
scala> "hello" += " world"
<console>:8: error: value += is not a member of java.lang.String
"hello" += " world"
Run Code Online (Sandbox Code Playgroud)
现在
scala> var h = "hello "
h: java.lang.String = "hello "
scala> h += "world"
scala> h
res24: java.lang.String = hello world
Run Code Online (Sandbox Code Playgroud)
我原以为第一个例子中的两个字符串表达式都会自然地进行评估以便允许操作.这种行为有充分的理由吗?
干杯!