19

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
0

2 Answers 2

36

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();
Sign up to request clarification or add additional context in comments.

Comments

6

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());  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.