\$\begingroup\$
\$\endgroup\$
4
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
}
return total
}
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?
asked Jul 22, 2011 at 19:37
2 Answers 2
\$\begingroup\$
\$\endgroup\$
There is already a sum
function:
def totalCost = value + children.map(_.totalCost).sum
answered Jul 23, 2011 at 9:59
\$\begingroup\$
\$\endgroup\$
1
A left-fold is an elegant solution too:
class Node (children:List[Node], value:Int) {
def totalCost : Int = (value /: children) (_ + _.totalCost)
}
answered Jul 23, 2011 at 17:32
-
\$\begingroup\$ Just a note for recent readers:
/:
is not used any more (it might even be deprecated, though I am not sure - see github.com/scala/bug/issues/9607). People writefoldLeft
instead. \$\endgroup\$Suma– Suma2020年11月06日 12:43:38 +00:00Commented Nov 6, 2020 at 12:43
lang-scala
totalCost
method, which works fine, but isn't very idiomatic. \$\endgroup\$