Newbie Scala question about simple math array operations

前端 未结 4 1374
自闭症患者
自闭症患者 2021-02-14 22:17

Newbie Scala Question:

Say I want to do this [Java code] in Scala:

public static double[] abs(double[] r, double[] im) {
  double t[] = new double[r.leng         


        
4条回答
  •  逝去的感伤
    2021-02-14 23:06

    Use zip and map:

    scala> val reals = List(1.0, 2.0, 3.0)
    reals: List[Double] = List(1.0, 2.0, 3.0)
    
    scala> val imags = List(1.5, 2.5, 3.5)
    imags: List[Double] = List(1.5, 2.5, 3.5)
    
    scala> reals zip imags
    res0: List[(Double, Double)] = List((1.0,1.5), (2.0,2.5), (3.0,3.5))
    
    scala> (reals zip imags).map {z => math.sqrt(z._1*z._1 + z._2*z._2)}
    res2: List[Double] = List(1.8027756377319946, 3.2015621187164243, 4.6097722286464435)
    
    scala> def abs(reals: List[Double], imags: List[Double]): List[Double] =
         | (reals zip imags).map {z => math.sqrt(z._1*z._1 + z._2*z._2)}
    abs: (reals: List[Double],imags: List[Double])List[Double]
    
    scala> abs(reals, imags)
    res3: List[Double] = List(1.8027756377319946, 3.2015621187164243, 4.6097722286464435)
    

    UPDATE

    It is better to use zipped because it avoids creating a temporary collection:

    scala> def abs(reals: List[Double], imags: List[Double]): List[Double] =
         | (reals, imags).zipped.map {(x, y) => math.sqrt(x*x + y*y)}
    abs: (reals: List[Double],imags: List[Double])List[Double]
    
    scala> abs(reals, imags)
    res7: List[Double] = List(1.8027756377319946, 3.2015621187164243, 4.6097722286464435)
    

提交回复
热议问题