Sar*_*ain 1 functional-programming scala immutability purely-functional scala-collections
我在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我将所有 var 转换为 val 并使其更具功能性吗?提前致谢!:)
使用.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
}
Run Code Online (Sandbox Code Playgroud)