【问题标题】:How to use reduce or fold to avoid mutable state如何使用 reduce 或 fold 来避免可变状态
【发布时间】:2023-03-19 23:46:01
【问题描述】:

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

    def someMethods(someArgs) = {
      var someMutableVariable = factory

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

        someMutableVariable
    }

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

【问题讨论】:

    标签: scala functional-programming mapreduce immutability fold


    【解决方案1】:

    如果你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 的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多