4

I have a slice that I want to replicate. For example, if xs = [1, 2, 3], and I need to replicate it 4 times, I would end up with ys = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3].

In Haskell, I would do something like this:

ys = take (4 * length xs) $ cycle xs

How might this be similarly done in Rust?

1 Answers1

5

Create an iterator from the array with iter, then an endlessly repeating iterator with cycle, then limit it to 4 cycles with take.

fn main() {
    let xs = [5,7,13];
    let ys = xs.iter()
                .cycle()
                .take(xs.len() * 4);

    for y in ys {
        println!("{}", y);
    }
}
Schwern
  • 153,029
  • 25
  • 195
  • 336