scala - 如何使用reduce或fold来避免可变状态

标签 scala functional-programming mapreduce immutability fold

我的代码中有一个可变变量,我想通过使用一些聚合函数来避免它。不幸的是我找不到以下伪代码的解决方案。

    def someMethods(someArgs) = {
      var someMutableVariable = factory

      val resources = getResourcesForVariable(someMutableVariable)
        resources foreach (resource => {
            val localTempVariable = getSomeOtherVariable(resource)
            someMutableVariable = chooseBetteVariable(someMutableVariable, localTempVariable)
        })

        someMutableVariable
    }

我的代码中有两个地方需要构建一些变量,然后在循环中将其与其他可能性进行比较,如果情况更糟,则将其替换为这个新的可能性。

最佳答案

如果您的resources变量支持它:

 //This is the "currently best" and "next" in list being folded over
 resources.foldLeft(factory)((cur, next) => 
   val local = getSomeOther(next)

   //Since this function returns the "best" between the two, you're solid
   chooseBetter(local, cur) 
 }

然后你就没有可变状态了。

关于scala - 如何使用reduce或fold来避免可变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22839852/

相关文章:

scala - 如何使用现有的 Intellij 项目来推进 SBT?

scala - 哪个scala集合最适合构建资源池

Clojure 不断和映射函数

用于收集参数的 Scala 镜头

JavaScript:为什么我的过滤功能不起作用?

hadoop - 为什么 HBase 支持的 Hive 表使用 MapReduce

scala - 重用 akka-stream 流的优雅方式

scala - Scala 的类型推断如何与类型边界一起工作?

hadoop - 使用Multiple Outputs Mapreduce将数据写入多个文件

hadoop - 在群集上部署Mahout作业