placplacboom placplacboom - 1 year ago 102
Scala Question

Scala - avoid use mutable variables

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 = { => {
var points = score
n.children.filter(n => n.valid == Some(true)).foreach(h => {
points = scoreNode(Some(h), 10, depth+1)

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download