Reputation: 2040
I have several lines of scala code which define a functionA that calls functionB repeatedly until n is zero(does functionB n times). Every iteration n decreases by 1, and x0 is updated as mentioned.
def functionA(c: Double, x0: Double, n: Int): Double = {
require(x0>0) //This is a must
while(n>0){
x0=functionB(c, x0) //functionB predefined
n--
}
x0
}
The problem is that the variables seem not able to change, as lines
x0=functionB(c, x0)
n--
are returning errors. If the current structure is not changed and total number of line remains the same, how can I do write the lines right?
Upvotes: 0
Views: 75
Reputation: 3854
The function parameters are val
s in Scala, so you cannot modify them.
Write your function recursively. Something like:
def functionA(c: Double, x0: Double, n: Int): Double = {
require(x0 > 0) //This is a must
if (n < 0) {
x0
} else {
functionA(c, functionB(c, x0), n - 1)
}
}
Upvotes: 8