2
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ 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? \$\endgroup\$ Commented Jul 23, 2011 at 19:27
  • \$\begingroup\$ I would second that. The question was to review the given totalCost method, which works fine, but isn't very idiomatic. \$\endgroup\$ Commented Jul 23, 2011 at 19:33
  • \$\begingroup\$ Probably it should be in stack overflow, it should be moved instead of getting closed. \$\endgroup\$ Commented Jul 24, 2011 at 9:50
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 25, 2011 at 3:07

2 Answers 2

7
\$\begingroup\$

There is already a sum function:

def totalCost = value + children.map(_.totalCost).sum
answered Jul 23, 2011 at 9:59
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\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 write foldLeft instead. \$\endgroup\$ Commented Nov 6, 2020 at 12:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.