scala - Scala 中的定点

标签 scala functional-programming higher-order-functions fixed-point-iteration

以下代码片段是否有快捷方式?

while (true) {
  val newClusters = this.iterate(instances, clusters)

  if (newClusters == clusters) {
    return clusters
  }

  clusters = newClusters
}

我想计算不动点,即执行一个函数,使其结果稳定。您是否知道任何适合我的目的的高阶函数?

最佳答案

改编自 Martin Odersky 的 Scala By Example 中的定点计算示例(“第一类函数”一章,第 5.3 节),

val instances = ...  // from question statement 

def isApproxFeasible(x: Clusters, y: Clusters) = some_distance_x_y < threshold

def fixedPoint(f: Clusters => Clusters)(initApprox: Clusters) = {
  def iterate(approx: Clusters): Clusters = {
    val newClusters = f(approx)
    if (isCloseEnough(approx, newClusters)) newClusters
    else iterate(newClusters)
  }
  iterate(initApprox)
}

where 函数 f: Clusters => Clusters提供新的候选集群,以及 initApprox对应于固定点的第一个初始猜测。功能 isApproxFeasible有助于确保先验阈值的终止。

关于scala - Scala 中的定点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22221243/

相关文章:

parsing - John Hughes 的确定性 LL(1) 使用 Arrow 和错误进行解析

haskell - 设计一种简单的静态类型化语言的类型系统(在Haskell中)

带接收器的函数的 Kotlin 扩展函数

scala - Spark-submit 类未找到异常

scala - 如何在IsTraversableLike中使用类型成员A?

java - Scala 的数值库

php - 函数数组的替代方案?

javascript - 将具有逻辑和用户界面的函数转换为高阶函数

php - array_filter 将索引数组转换为关联数组

scala - 从 1 个元素的 Scala 集合中获取元素