Using repeat I can create an iterator which repeats one element. But how can I repeat multiple values infinitely? For example:
let repeat_1 = repeat(1); // 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
let repeat_123 = repeat([1, 2, 3]); // 1, 2, 3, 1, 2, 3, 1, 2, ... // or similar
You can use .cycle()
like this:
fn main() {
let values = [1, 2, 3];
let repeat_123 = values.iter().cloned().cycle();
for elt in repeat_123.take(10) {
println!("{}", elt)
}
}
It works on any iterator that can be cloned (the iterator, not its elements).
Please note that the .cloned()
adaptor is incidental! It translates the by-reference iterator elements of the slice's iterator into values.
A simpler way to write this particular sequence is:
let repeat_123 = (1..4).cycle();
Found it out:
One can also repeat
arrays, tuples or slices (depending on the needs).
For example:
let repeat_123 = std::iter::repeat([1, 2, 3]); // [1, 2, 3], [1, 2, 3], ...
This iterator is nested, however, to flatten it, use flatmap
let pattern = &[1, 2, 3];
let repeat_123_flat = std::iter::repeat(pattern).flat_map(|x| x.iter());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With