尝试在Swift中使用Flatmap和Map添加

时间:2018-09-05 15:52:25

标签: swift higher-order-functions flatmap

我尝试在Playground中使用以下代码将二维数组转换为一维数组后添加:

let twoDimensionalArray = [[1, 3, 5], [2, 4, 6], [12, 15, 16]]
let oneDimensionalArray = twoDimensionalArray.flatMap { $0.map { $0 += 2 } }
print(oneDimensionalArray)

但是我收到错误:

  

变异运算符的左侧不可更改:'$ 0'是不变的

我还发现Apple Documentation中不推荐使用flatmap方法,所以我应该做些什么?

1 个答案:

答案 0 :(得分:1)

您几乎是正确的。您只需要删除=

let twoDimensionalArray = [[1, 3, 5], [2, 4, 6], [12, 15, 16]]
let oneDimensionalArray = twoDimensionalArray.flatMap { $0.map { $0 + 2 } }
print(oneDimensionalArray) // [3, 5, 7, 4, 6, 8, 14, 17, 18]

您可以通过对值($0)进行操作和其他操作来对更改($0 += 2)进行更改,而不是直接更改(即#include <Eigen/Eigen> #include <iostream> using namespace Eigen; template <typename Derived> auto f(DenseBase<Derived>& x) { auto max_x = x.colwise().maxCoeff().eval(); x = x.rowwise() + max_x; return max_x; } int main() { Array<float, 3, 3> M1, M2; M1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; M2 = M1; std::cout << M1 << "\n"; std::cout << "no transpose\n"; Array<float, 3, 1> max_x = f(M1); std::cout << M1 << "\n"; std::cout << max_x << "\n"; std::cout << "transpose\n"; auto m2_t = M2.transpose(); Array<float, 1, 3> max_x2 = f(m2_t); std::cout << M2 << "\n"; std::cout << max_x2 << "\n"; } )。