功能编程方式做阵列转换

时间:2015-02-25 16:08:02

标签: swift functional-programming

struct MapVector {
    var distance: Double
    var bearing: Double
}

func distanceAndBearing() -> [MapVector] {
    var points = self.mapPoints
    var currPoint:CLLocation = points.first!
    points.removeAtIndex(0)

    var result: [MapVector] = []
    for point: CLLocation in points {
        let calc = PointCalculator(initialPoint: currPoint, nextPoint: point)

        let v = MapVector(distance: calc.pointDistance, bearing: calc.bearing)
        result.append(v)

        currPoint = point
    }

    return result
}

我正在使用地图坐标在Swift上工作。我有一个CLLocations数组,我想从中创建一系列距离和方位。上面的代码(为了便于阅读而略微简化,因此可能不是100%正确)实现了这一点,但我想以更简洁的方式做到这一点。这是可以通过地图或过滤器完成的吗?仍然试图绕过FP的做事方式。

2 个答案:

答案 0 :(得分:1)

以下是除计算外的同一问题的简化示例:

let numbers = [3, 7, 2, 8, 3, 7, 5]
let result = numbers.isEmpty ? [] :
    map(zip(numbers, numbers[1..<numbers.count])) {
        (x, y) in
        return (diff: x - y, mult: x * y)
}

result[0].diff // -4
result[0].mult // 21

在这里,我计算数字的差异和乘法。 请注意,这仅适用于Swift 1.2 如果您需要早期版本,则应探索Zip2

的使用

答案 1 :(得分:0)

这里提供的是我提出的替代解决方案: -

func distanceAndBearing2() -> [MapVector]
{
    // make the removeAtIndex(0) part safe
    if (self.mapPoints.count == 0) {
        return []
    }

    var t2 = self.mapPoints
    t2.removeAtIndex(0)

    let t3 = zip(self.mapPoints, t2)

    return Array(t3).map({
        (p1, p2) in
        return PointCalculator(initialPoint: p1, nextPoint: p2).toMapVector()
    })
}

这使用Xcode 6.3 Beta 2的新zip方法,我将转换为MapVector转换为PointCalculator结构

func distanceAndBearing3() -> [MapVector] {
    // make the shift part safe
    if (self.mapPoints.count == 0) {
        return []
    }

    var points = self.mapPoints
    var currPoint = points.shift()!

    return points.map {
        point in

        let initialPoint = currPoint
        currPoint = point

        return LocationPair(initialPoint: initialPoint,
            nextPoint: point).toMapVector()
    }
}

此版本在PointCalculator结构上使用相同的toMapVector方法,但使用map函数外部的变量,该变量由map函数更新;感觉就像它没有&#34;正确&#34;