문제

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?

도움이 되었습니까?

해결책

The function parameters are vals 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)
  }
}  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top