在Scala中使用循环时,让事情变得不可改变。

问题描述 投票:1回答:2

我已经用Scala写了几行代码,但不知道如何用不可变变量(val)来做同样的事情。任何帮助将是非常感激的。

class Test {

  def process(input: Iterable[(Double, Int)]): (Double, Int) = {
    var maxPrice: Double = 0.0
    var maxVolume: Int = 0

    for ((price, volume) <- input) {
      if (price > maxPrice) {
        maxPrice = price
      }
      if (volume > maxVolume) {
        maxVolume = volume
      }
    }

    (maxPrice, maxVolume)
  }
}

谁能帮我把所有的var转换为val,并使其更加实用?:)

scala functional-programming immutability scala-collections purely-functional
2个回答
7
投票

使用 .foldLeft:

def process(input: Iterable[(Double, Int)]): (Double, Int) =
  input.foldLeft(0.0 -> 0) { case ((maxPrice, maxVolume), (price, volume)) =>
    val newPrice = if (maxPrice < price) price else maxPrice
    val newVolume = if (maxVolume < volume) volume else maxVolume
    newPrice -> newVolume
  }

2
投票

比较而言,这里是一个尾部递归的解决方案。

  def process(input: Iterable[(Double, Int)]): (Double, Int) = {
    @tailrec def loop(remaining: Iterable[(Double, Int)], maxPrice: Double, maxVolume: Int): (Double, Int) = {
      remaining match {
        case Nil => maxPrice -> maxVolume
        case (price, volume) :: tail =>
          val newPrice = if (maxPrice < price) price else maxPrice
          val newVolume = if (maxVolume < volume) volume else maxVolume
          loop(tail, newPrice, newVolume)
      }
    }
    loop(input, 0, 0)
  }

和相应的jmh基准

@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So61366933 {
  def mario(input: Iterable[(Double, Int)]): (Double, Int) = {
    @tailrec def loop(remaining: Iterable[(Double, Int)], maxPrice: Double, maxVolume: Int): (Double, Int) = {
      remaining match {
        case Nil => maxPrice -> maxVolume
        case (price, volume) :: tail =>
          val newPrice = if (maxPrice < price) price else maxPrice
          val newVolume = if (maxVolume < volume) volume else maxVolume
          loop(tail, newPrice, newVolume)
      }
    }
    loop(input, 0, 0)
  }


  def mateusz(input: Iterable[(Double, Int)]): (Double, Int) =
    input.foldLeft(0.0 -> 0) { case ((maxPrice, maxVolume), (price, volume)) =>
      val newPrice = if (maxPrice < price) price else maxPrice
      val newVolume = if (maxVolume < volume) volume else maxVolume
      newPrice -> newVolume
    }

  import scala.util.Random._
  def arbTuple: (Double, Int) = nextDouble() -> nextInt()
  val input = List.fill(1000)(arbTuple)

  @Benchmark def foldLeft = mateusz(input)
  @Benchmark def tailRec = mario(input)
}

哪儿

sbt "jmh:run -i 5 -wi 5 -f 2 -t 1 bench.So61366933"

产出

[info] Benchmark             Mode  Cnt       Score      Error  Units
[info] So61366933.foldLeft  thrpt   10   80999.752 ± 2118.095  ops/s
[info] So61366933.tailRec   thrpt   10  259875.842 ± 7718.674  ops/s
© www.soinside.com 2019 - 2024. All rights reserved.