import 'dart:collection';
import 'package:collection/collection.dart';
void main() {
final listA = [0, 1, 2];
final listB = ['aaa', 'bbb', 'ccc'];
final zipped = IterableZip([listA, listB]);
for (final [valueAsInt, valueAsString] in zipped) {
print(valueAsString.substring(valueAsInt)); // type error. (The method 'substring' isn't defined for the type 'Object'.)
}
final zipped2 = IterableZip2(listA, listB);
for (final (valueAsInt, valueAsString) in zipped2) {
print(valueAsString.substring(valueAsInt)); // no type error. (output aaa, bb, c)
}
}
Implementation Example
import 'dart:collection';
class IterableZip2<T, U> extends IterableBase<(T, U)> {
final Iterable<T> _iterablesT;
final Iterable<U> _iterablesU;
IterableZip2(Iterable<T> iterablesT, Iterable<U> iterablesU)
: _iterablesT = iterablesT,
_iterablesU = iterablesU;
@override
Iterator<(T, U)> get iterator {
return _IteratorZip2<T, U>(_iterablesT.iterator, _iterablesU.iterator);
}
}
class _IteratorZip2<T, U> implements Iterator<(T, U)> {
final Iterator<T> _iteratorT;
final Iterator<U> _iteratorU;
(T, U)? _current;
_IteratorZip2(Iterator<T> iteratorsT, Iterator<U> iteratorU)
: _iteratorT = iteratorsT,
_iteratorU = iteratorU;
@override
bool moveNext() {
if (!_iteratorT.moveNext()) {
_current = null;
return false;
}
if (!_iteratorU.moveNext()) {
_current = null;
return false;
}
_current = (_iteratorT.current, _iteratorU.current);
return true;
}
@override
(T, U) get current => _current ?? (throw StateError('No element'));
}
Rust pub fn zip<A, B>(a: A, b: B) -> Zip<<A as IntoIterator>::IntoIter, <B as IntoIterator>::IntoIter> where A: IntoIterator, B: IntoIteratorhttps://doc.rust-lang.org/std/iter/fn.zip.html
Implementation Example
Examples of zip functions in other languages
infix fun <T, R> Array<out T>.zip( other: Array<out R>): List<Pair<T, R>>
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/zip.htmlpub fn zip<A, B>(a: A, b: B) -> Zip<<A as IntoIterator>::IntoIter, <B as IntoIterator>::IntoIter> where A: IntoIterator, B: IntoIterator
https://doc.rust-lang.org/std/iter/fn.zip.htmlzip :: [a] -> [b] -> [(a, b)]
https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:zipzip :: forall a b. Array a -> Array b -> Array (Tuple a b)
https://pursuit.purescript.org/packages/purescript-arrays/7.3.0/docs/Data.Array#v:zipzip : List a -> List b -> List ( a, b )
https://package.elm-lang.org/packages/elm-community/list-extra/latest/List-Extra#zip-