motoko-base
motoko-base copied to clipboard
feat: add `Iter.enumerate` method
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;
}
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
@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
)
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
Let me ask an innocent question... Isn't this just a zip
of the passed-in iterator with some unbounded range?
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.
@kentosugama @ggreif any reason not to merge this?
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 zip
s it with the above letters.vals()
.
Seems like there aren't any plans to merge this.