Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an iterator that repeats multiple values infinitely?

Tags:

iterator

rust

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
like image 212
Kapichu Avatar asked Feb 10 '15 16:02

Kapichu


2 Answers

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();
like image 196
bluss Avatar answered Oct 11 '22 03:10

bluss


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());  
like image 4
Kapichu Avatar answered Oct 11 '22 03:10

Kapichu