Adding an index with functional methods like map, reduce, filter

Here's a quick draft pitch before I can expand on it. The gist is to add an index to the functional methods, so it can allow for something like (note mapi is used to differentiate it from map)

let arrayNumbers = [1, 2, 3, 4, 5, 6]
let oddOnes = arrayNumbers.mapi{(number, index) in 
    if index % 2 == 0 { 
        return number 
    } else {
        return number * 2
    }
}

in case of reduce, filter etc it can be used in a similar fashion where the index helps to eliminate loops that would otherwise look like

let numArray = [1, 2, 3, 4, 5]
var index = 0
for number in numArray {
    if index % 5 == 0 {
    // do something
    } 
    index += 1
}

Would also appreciate if someone can help creating a proposal on this, I am sure this will be quite useful

thanks,

Jayant

You can use Sequence.enumerated() for these use-cases quite easily, so I don't think introducing new versions of the functional methods is worth it.

3 Likes

Vielen danke @ahti,
but if we were to benchmark the speeds of processing using loops (sequence.enumerated()) vs functional, do they stack up comparable?

Maybe the example of the loop is not well presented, but the point here is about

  • functionality - ability to use an index
  • speed - achieving it faster/efficiently

if these two are achieved by Sequence.enumerated, then I believe this should work for me.

thanks,

This is the meat of enumerated(). It doesn't do much except incrementing the counter and passing on the value, plus it's mostly inlineable, so I'd assume it would be reasonably fast, but I don't have any numbers to back that up.

(Oh btw, you don't need to use enumerated with loops, you can just as well do something like someSequence.enumerated().map { ... })

4 Likes

I don’t think we need these methods. It’s trivial to write x.indices.map{ … }, and access the values as needed via subscript.

1 Like

Related topic: Add forEachWithIndex to Array

Thanks @ahti, that works for me, the point is there are so many little details around these. :+1:t3: