Scala中的不动点

Scala中的不动点,scala,functional-programming,higher-order-functions,fixed-point-iteration,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的不动点计算示例(第5.3节“第一

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

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

  if (newClusters == clusters) {
    return clusters
  }

  clusters = newClusters
}

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

根据Martin Odersky的Scala的不动点计算示例(第5.3节“第一类函数”一章)改编而成

val实例=…//来自问题陈述
def isApproxPersibility(x:簇,y:簇)=一些距离×y<阈值
def固定点(f:Clusters=>Clusters)(初始近似值:Clusters)={
def迭代(近似:簇):簇={
val newClusters=f(近似值)
如果(isclosevery(大约,newClusters))newClusters
else迭代(newClusters)
}
迭代(初始近似值)
}

其中,函数
f:Clusters=>Clusters
提供新的候选集群,
initApprox
对应于固定点上的第一个初始猜测。函数<代码>IsApproxCompliable有助于确保终止先验阈值

另一种方法是结合著名的单线斐波那契数计算()和
takeWhile

val reductions = Stream.iterate(clusters)(this.iterate(instances, _))
(reductions, reductions.tail).zipped.takeWhile { case (p, n) => p != n }.last._1
另一种不需要在内存中构造流对象的方法是使用迭代器:

Iterator.iterate(clusters)(this.iterate(instances, _))
  .sliding(2)
  .dropWhile { case prev +: next +: _ => prev != next }
  .next()
  .head

尽管命令式解决方案可能更有效,因为它是一个没有流构造或闭包调用的简单循环。

对不起,除了使用递归之外,我看不出我的方法有什么不同。不幸的是,它并没有使我的代码变得更短或更可读。不用担心,将“高级函数”误解为“一流函数”:)也许库/包函数可能是传达查询的另一个名称:)
Iterator.iterate(clusters)(this.iterate(instances, _))
  .sliding(2)
  .dropWhile { case prev +: next +: _ => prev != next }
  .next()
  .head