进行数组转换的函数式编程方式 [英] Functional programming way of doing array conversion

查看:93
本文介绍了进行数组转换的函数式编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var结果:[MapVector] = []
为点:CLLocation为点{
let calc = PointCalculator(initialPoint:currPoint ,nextPoint:point)

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

currPoint =点
}

返回结果
}

我在使用地图坐标的应用程序中使用Swift。我有一个CLLocations数组,我想从中创建一个距离和方位数组。上面的代码(它的可读性稍微简化,所以可能不是100%正确)达到了,但我想以一种更好的方式来做到这一点。这是可以通过地图或过滤器完成的事情吗?仍然试图让我的头脑围绕FP的做事方式。

解决方案

这是一个简单的例子,计算:

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

结果[0] .diff // -4
结果[0] .mult // 21

这里我计算数字的差异和乘法。
注意这只适用于Swift 1.2
如果你需要它的早期版本,你应该探索使用 Zip2


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
}

I am working in Swift on an application using map coordinates. I have a an array of CLLocations from which I would like to create an array of distances and bearings. The above code (its slightly simplified for readability, so may not be 100% correct) achieves that but I'd like to do it in a neater way. Is this something that can be done with map or filter? Still trying to get my head around the FP way of doing things.

解决方案

Here is a simplified example for the same problem except the calculations:

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

Here I compute the differences and the multiplications of the numbers. Note this will work only for Swift 1.2 In case you need it for earlier version, you should explore the use of Zip2.

这篇关于进行数组转换的函数式编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆