motoko-base icon indicating copy to clipboard operation
motoko-base copied to clipboard

feat: add `Iter.enumerate` method

Open q-uint opened this issue 1 year ago • 7 comments

Takes an iterator and returns a new iterator that produces the same elements with corresponding indices.

import Iter "mo:base/Iter"; 

let letters = [ "a", "b", "c" ];
let enumeratedIter = Iter.enumerate(letters.vals());
assert(?(0, "a") == enumeratedIter.next());
assert(?(1, "b") == enumeratedIter.next());
assert(?(2, "c") == enumeratedIter.next());
assert(null == enumeratedIter.next());

Simplifies:

var i = 0;
for (l in letters.vals()) {
  // Do somthing with `i` and `l`.
  i += 1;
}

q-uint avatar Mar 28 '23 12:03 q-uint

Dear @di-wu,

In order to potentially merge your code in this open-source repository and therefore proceed with your contribution, we need to have your approval on DFINITY's CLA[^1].

If you decide to agree with it, please visit this issue and read the instructions there.

— The DFINITY Foundation [^1]: Contributor License Agreement

dfinity-droid-prod[bot] avatar Mar 28 '23 12:03 dfinity-droid-prod[bot]

@kentosugama @crusso Would love to see this merged in - sometimes just need a count aware iterator without needing to provide a function (like in Iter.iterate)

ByronBecker avatar Apr 16 '23 01:04 ByronBecker

Dear @q-uint,

In order to potentially merge your code in this open-source repository and therefore proceed with your contribution, we need to have your approval on DFINITY's CLA[^1].

If you decide to agree with it, please visit this issue and read the instructions there.

— The DFINITY Foundation [^1]: Contributor License Agreement

dfinity-droid-prod[bot] avatar Apr 19 '23 16:04 dfinity-droid-prod[bot]

Let me ask an innocent question... Isn't this just a zip of the passed-in iterator with some unbounded range?

ggreif avatar Apr 20 '23 19:04 ggreif

Isn't this just a zip of the passed-in iterator with some unbounded range?

In a way yes, currently only the List and Buffer structs have the zip operation defined afaik. Might be interesting to also support this for iterators.

q-uint avatar Apr 21 '23 11:04 q-uint

@kentosugama @ggreif any reason not to merge this?

crusso avatar Jun 27 '23 10:06 crusso

I am a bit concerned about

  • utility: this is a very specific function
  • heap traffic: this tends to create a lot of pairs in the heap that end up as garbage
  • naming: this really enumerating things?

IMHO what we need is a rangeFrom iterator that gives the naturals (open ended) and then zips it with the above letters.vals().

ggreif avatar Jun 27 '23 11:06 ggreif

Seems like there aren't any plans to merge this.

q-uint avatar May 19 '24 11:05 q-uint