在 Swift 中使用嵌套 reduce

Using nested reduce in Swift

我有一个包含 Double 数组的数组,如屏幕截图所示:

我的目标是得到每个数组的 Double 个元素相乘的总和。这意味着,我想乘以每个数组的所有元素,然后,在我的例子中,我将有 3 个值,所以我得到它们的总和。

我想使用 reduceflatMap?或任何优雅的解决方案。

我尝试了什么?

totalCombinations.reduce(0.0) { [=11=] + ([0]*[1]*[2])  }

但这只有在我知道包含双精度数组的大小时才有效。

你可以这样写:

let totalCombinations: [[Double]] = [
    [2.4,1.45,3.35],
    [2.4,1.45,1.42],
    [2.4,3.35,1.42],
    [1.45,3.35,1.42],
]

let result = totalCombinations.reduce(0.0) {[=10=] + .reduce(1.0) {[=10=] * } }

print(result) //->34.91405

但我不确定是不是"elegant"。

也许这就是您要找的

let a = [1.0, 2.0, 3.0]
let b = [4.0, 5.0, 6.0]
let c = [7.0, 8.0, 9.0, 10.0]

let d = [a, b, c]

let sum = d.reduce(0.0) { [=10=] + .reduce(1.0) {[=10=] * }}
print(sum) // prints 5166.0

给定这些值

let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]

让我们来看看几种可能的方法

解决方案 #1

let sum =  lists.reduce(0) { [=11=] + .reduce(1, combine: *) }

解决方案 #2

如果你定义这个扩展

extension SequenceType where Generator.Element == Double {
    var product : Double { return reduce(1.0, combine: *) }
}

那你可以写

let sum = lists.reduce(0) { [=13=] + .product }

解决方案 #3

使用上面定义的扩展名你也可以写

let sum = lists.map { [=14=].product }.reduce(0, combine:+)

解决方案 #4

如果我们定义这 2 个后缀运算符

postfix operator +>{}
postfix func +>(values:[Double]) -> Double {
    return values.reduce(0, combine: +)
}

postfix operator *>{}
postfix func *>(values:[Double]) -> Double {
    return values.reduce(1, combine: *)
}

我们可以写

lists.map(*>)+>