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

Kam*_*nek 2 functional-programming scala 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
    }
Run Code Online (Sandbox Code Playgroud)

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

whe*_*ies 5

如果你的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) 
 }
Run Code Online (Sandbox Code Playgroud)

然后你没有可变的状态.