# Scala list folding

I'm trying to learn scala. It's hard.

I currently have a tree in the form

class Node(children:List[Node], value:Int){

}


I want to calculate a total cost defined by value + the sum of the totalcost of the children. My java background made me do this:

def totalCost() {
var total = value
for (child <- children){
total = total+child.totalCost
}
}


now I know I should be folding or reducing, but it's not coming out. Could some of you frendly helpers give me a hand here?

• I don't quite understand how this question is not within scope. @Michael K: Could you review your closure, and if it is in fact out of scope, explain how, so I won't be asking out of scope questions on this site again? – Martijn Jul 23 '11 at 19:27
• I would second that. The question was to review the given totalCost method, which works fine, but isn't very idiomatic. – Landei Jul 23 '11 at 19:33
• Probably it should be in stack overflow, it should be moved instead of getting closed. – Cem Kalyoncu Jul 24 '11 at 9:50
• I apologize; this was flagged as OT and I didn't read the post closely enough. This does have working code and is on topic here. – Michael K Jul 25 '11 at 3:07

There is already a sum function:
def totalCost = value + children.map(_.totalCost).sum

class Node (children:List[Node], value:Int) {