【问题标题】:Replacement of if with higher order method用高阶方法替换 if
【发布时间】:2019-10-28 19:43:59
【问题描述】:

最不推荐在 Scala 中使用 if 块进行分布式计算。我有代码,我想用 Scala 高阶方法替换 if。我怎样才能做到这一点。 详细代码给Here

包含 if 块的部分代码是。

var bat = DenseVector.fill(N)(new BAT12(d , MinVal , MaxVal ))
bat.foreach{x => x.BestPosition = x.position;x.fitness =  Sphere(x.position)  ; x.BestFitness = x.fitness}
bat.foreach(x =>
if(x.BestFitness < GlobalBest_Fitness)
{
 GlobalBest_Fitness =x.BestFitness ;GlobalBest_Position = x.BestPosition
})

【问题讨论】:

  • 问题不在于if,问题在于使用了可变数据结构。而这与分布式计算无关。

标签: scala functional-programming distributed-computing


【解决方案1】:

试试

bat.filter(_.BestFitness < GlobalBest_Fitness).foreach { x =>
  GlobalBest_Fitness = x.BestFitness
  GlobalBest_Position = x.BestPosition
}

【讨论】:

  • 解决方案很好,但过滤器适用于 List,Array ,不适用于 DenseVector
  • 尝试在DenseVector 上调用toArraytoScalaVector 就像这样bat.toArray.filter(...
【解决方案2】:

在foreach之前做一个过滤,以if条件作为过滤条件。然后无条件执行foreach。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多