3

下面的代碼段是否有快捷方式?Scala中的固定點

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

    if (newClusters == clusters) { 
    return clusters 
    } 

    clusters = newClusters 
} 

我想計算固定點,即執行一個函數,使其結果穩定。你是否知道任何適合我的目的的高階函數?

回答

1

由馬丁·奧德斯基(第「一流功能」,第5.3節)從固定點的計算例的適配從Scala中通過實施例

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) 
} 

其中功能f: Clusters => Clusters提供新的候選聚類,和initApprox對應於第一個對固定點的初始猜測。功能isApproxFeasible有助於確保終止先驗閾值。

+0

對不起,但我沒有看到我的方法有任何區別,除了你使用遞歸的事實。不幸的是,它不會讓我的代碼更短或更易讀。 – user3267915

+0

不用擔心,通過「頭等功能」誤解了「更高級功能」:)也許庫/包函數可能是傳達查詢的另一個命名:) – elm