简体   繁体   中英

Scala: value < is not a member of Array[Double]

I'm trying to replace the value Array of x if is x is less than 0.000001 then x will be equal to 0.000001. Then return log(x).

Here is my scala code:

def log(args: Array[Double]){
  var x = Array.fill(20){math.random}

    if(x < 0.000001){ // error: value < is not a member of Array[Double]
      x == 0.000001}
    else{scala.math.log(x)} // error: type mismatch, it found Array[Double], required: double

 }

Thanks for your help! I'm really really new to Scala, no prior experience on coding except R

This will give you a new array with the changed values:

val xx = x.map { y => if (y < 0.000001) 0.000001 else scala.math.log(y) }

I am going to guess that you also want to return the new array from the method, so:

def log(args: Array[Double]): Array[Double] = {
  var x = Array.fill(20){math.random}
  x.map { y => if (y < 0.000001) 0.000001 else scala.math.log(y) }
}

In addition to radumanolescu's answer, you can also apply map function with case as shown below (it's a good trick to have the sleeve especially for nested ifs or value bindings):

x.map {
    case y if y >= 0.000001 => scala.math.log(y)
    case y => y
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM