placplacboom - 8 months ago 72

Scala Question

I have a function that perform a calc but i'm using a var to receive the value of a recursive function and i would like to avoid mutable variables.

`def scoreNode(node:Option[Tree], score:Double = 0, depth:Int = 0):Double = {`

node.map(n => {

var points = score

n.children.filter(n => n.valid == Some(true)).foreach(h => {

points = scoreNode(Some(h), 10, depth+1)

})

points

}).getOrElse(score)

}

How can i rewrite this piece of code without a mutable variable? I've tried

Answer

What you are essentially doing is summing something over all the nodes in a tree. Try to write a more idiomatic code, like this.

```
def scoreNode(node:Option[Tree], depth:Int = 0):Double =
(for {
n <- node
h <- n.children
if h.valid == Some(true)
res = scoreNode(Some(h), depth + 1) + scala.math.pow(0.8, depth)
} yield res).sum
```

I do not guarantee this works completely. It is your homework to make it right.

Source (Stackoverflow)