闭包参数列表的上下文类型需要1个参数,但指定了2个参数

时间:2016-01-16 01:26:34

标签: algorithm swift2 xcode7.2

我正在尝试使用swift 2.1:http://users.eecs.northwestern.edu/~wkliao/Kmeans/

来使用此算法

虽然我在这一行收到错误:

  return map(Zip2Sequence(centroids, clusterSizes)) { Cluster(centroid: $0, size: $1) }

这是完整的功能:

func kmeans<T : ClusteredType>(
        points: [T],
        k: Int,
        seed: UInt32,
        distance: ((T, T) -> Float),
        threshold: Float = 0.0001
    ) -> [Cluster<T>] {

    let n = points.count
    assert(k <= n, "k cannot be larger than the total number of points")

    var centroids = points.randomValues(seed, num: k)
    var memberships = [Int](count: n, repeatedValue: -1)
    var clusterSizes = [Int](count: k, repeatedValue: 0)

    var error: Float = 0
    var previousError: Float = 0

        repeat {
            error = 0
            var newCentroids = [T](count: k, repeatedValue: T.identity)
            var newClusterSizes = [Int](count: k, repeatedValue: 0)

            for i in 0..<n {
                let point = points[i]
                let clusterIndex = findNearestCluster(point, centroids: centroids, k: k, distance: distance)
                if memberships[i] != clusterIndex {
                    error += 1
                    memberships[i] = clusterIndex
                }
                newClusterSizes[clusterIndex]++
                newCentroids[clusterIndex] = newCentroids[clusterIndex] + point
            }
            for i in 0..<k {
                let size = newClusterSizes[i]
                if size > 0 {
                    centroids[i] = newCentroids[i] / size
                }
            }

            clusterSizes = newClusterSizes
            previousError = error
        } while abs(error - previousError) > threshold

        return map(Zip2Sequence(centroids, clusterSizes)) { Cluster(centroid: $0, size: $1) }
}

如何更改此设置以删除此错误?

1 个答案:

答案 0 :(得分:2)

据我了解,您正尝试以下内容:

return (0..<k).map { Cluster(centroid: centroids[$0], size: clusterSizes[$0]) }

来自 Swift Zip2Sequence<Sequence1, Sequence2>文档:

  

由两个基础序列构建的一对序列,其中   i对的元素是每个底层元素的i个元素   序列

Zip2Sequence<[T], [Int]>生成器的元素是(T, Int)元组。 您可以通过索引访问此元组的各个元素。

因此,以下代码应该适合您:

return Zip2Sequence(centroids, clusterSizes).map { Cluster(centroid: $0.0, size: $0.1) }