Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #350 Create an enumerated collection

Generate a collection of "enumerated" values.

For example, Python's `enumerate` built-in function.

https://docs.python.org/3/library/functions.html#enumerate

import static java.util.Arrays.stream;
import static java.util.stream.IntStream.iterate;
import java.util.Iterator;
import java.util.List;
record E<T>(int i, T value) {}
<T> List<E<T>> enumerate(T ... a) {
    Iterator<T> g = stream(a).iterator();
    return iterate(0, x -> g.hasNext(), i -> i + 1)
        .mapToObj(i -> new E<>(i, g.next()))
        .toList();
}
e = enumerate(a)
a = %w(abc xyz)
a.map.with_index{|v, i| [i, v] }

New implementation...
< >
reilas