0
var data: [[String]] = ...
let pos = data.compactMap { Int($0[posColumn]) }
let neg = data.compactMap { Int($0[negColumn]) }

let sum = ?? { pos + neg }

I have a csv data, a column for positive values and a column for negative. Using data.compactMap I get two arrays for both. How can I get [Int] for sum using functional programming?

2 Answers 2

3

You want to sum across your two columns to create a third column.

Use zip(_:_:) to combine the arrays and map(_:) to sum them:

let sum = zip(pos, neg).map(+)

what if I need to get sum AND divide by some number? So, there will be 3 arrays: pos, neg, tot. (pos + neg) / tot

Since zip only works with 2 sequences, you could instead map over the indices of one of your arrays:

let result = pos.indices.map { (pos[$0] + neg[$0]) / tot[$0] }
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! To make it more complex: what if I need to get sum AND divide by some number? So, there will be 3 arrays: pos, neg, tot. (pos + neg) / tot
As tot is an array with corresponding values, it should be like: let result = zip(pos, neg, tot).map { ($0 + $1)/$2 } - but zip takes only 2 args.
Oh, in that case let result = pos.indices.map { (pos[$0] + neg[$0]) / tot[$0] }
0
let sum = (pos + neg).reduce(0, +)

3 Comments

This code-only answer would be better if it explained why the code works.
@jkdev you mean I should mention how this code works?
Yes, exactly. That would make the answer easier to understand, and more valuable for other people who find it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.