Rewrite cpp for loop in rust

Hi.

How to write the following c++ for loop in rust?

for (int i = 0, exp = 1; i < r.size(); i++, exp = (exp << 2) % SEED) {
  // do something
}

This is what I have tried but it looks messy

let exp_iter = [1].into_iter().chain(
                [0_u8].into_iter().cycle().scan(1, |e, _x| {
                    *e = (*e << 2) % Self::SEED;
                    Some(*e)
                })
            );

for (i, exp) in (0..r.len()).zip(exp_iter) {
  // do something
}
for i in 0..r.len() {
    let exp = (1 << 2*i) % Self::SEED;
    // do something
}

Just because iterators exist doesn't mean you have to use them. I'd argue this version is also a hell of a lot easier to understand.

7 Likes

I generally agree that going all-in on iterators isn't needed here. But there are nicer ways to define that iterator too IMO.

    let exps = std::iter::successors(Some(1), |exp| Some((exp << 2) % SEED));
    for (exp, i) in exps.zip(0..r.size()) {
        println!("{i}: {exp}");
    }    

Or if you use it a lot, write some fn exps() -> impl Iterator<Item = u64>.

Or code a custom struct that implements Iterator (it's not as daunting as you may think).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.