5

I have a range, that I want to reverse if a condition is satisfied. Since for i in 0..9 will iterate the same way as for i in 9..0 simply swapping out the numbers will not work. Also (0..9).stepy_by(-1) is not an option as .step_by() only accepts a usize. Therefore I tried so implement something like the following:

fn create_range(rev: bool) -> Range<usize> {
    if rev {
        0..9
    } else {
        (0..9).rev()
    }
}

Which unfortunately also des not work since 0..9 returns a Range<usize> but (0..9).rev() returns a Rev<Range<usize>> so the types do not match.

I ended up putting everything that I call within the loop in a function but I am not really satisfied with that.

if rev {
    for i in (0..9).rev() {
        do_stuff(i);
    }
} else {
    for i in 0..9 {
        do_stuff(i);
    }
}

The question is: Would it be simply possible to reverse a range if a condition is satisfied?

3 Answers 3

5

itertools has the type Either that can be used to return either of two compatible iterators:

use itertools; // 0.8.2

fn create_range(
    rev: bool,
) -> itertools::Either<impl Iterator<Item = usize>, impl Iterator<Item = usize>> {
    if !rev {
        itertools::Either::Left(0..9)
    } else {
        itertools::Either::Right((0..9).rev())
    }
}

fn main() {
    println!("Not reversed:");
    for a in create_range(false) {
        println!("{}", a);
    }

    println!("Reversed:");
    for a in create_range(true) {
        println!("{}", a);
    }
}

(Permalink to the playground)

3
  • 1
    I don't know who down voted this answer. For me this answer the question. Dec 24, 2019 at 11:57
  • This is a good answer to the question. Unfortunately when simplifying it I left out, that I return a tuple of ranges which I can't get to work with generics. See the Playgroud. Is there an error or is a tuple not working with generics?
    – sbstnzmr
    Dec 25, 2019 at 13:15
  • 1
    @sezi80 from the usage, it looks like you want to return a tuple of Eithers, rather than an Either of tuples.
    – mcarton
    Dec 25, 2019 at 13:28
1

Another solution without itertools:

fn create_range(rev: bool) -> impl Iterator<Item = usize> {
    let (mut start, step) = if rev {
        (9usize, usize::max_value())
    } else {
        (usize::max_value(), 1)
    };

    std::iter::repeat_with(move || {
        start = start.wrapping_add(step);
        start
    })
    .take(9)
}

fn main() {
    println!("Not reversed:");
    for a in create_range(false) {
        println!("{}", a);
    }

    println!("Reversed:");
    for a in create_range(true) {
        println!("{}", a);
    }
}

(Permalink to the playground)

This is a bit more complicated and won't generalize as easily to things that are not ranges. It might be a tiny bit faster as well. The dance with usize::max_value() and wrapping_add is necessary to avoid overflow checks, but is perfectly defined.

3
  • You can probably edit your above answer, no need for double posting. Dec 24, 2019 at 14:09
  • @DanielFath Those are two different solutions. Posting two different answers to the same question is fine on SO.
    – mcarton
    Dec 24, 2019 at 14:12
  • 1
    I don't think these are really multiple independent answers meta.stackoverflow.com/questions/384665/… Dec 24, 2019 at 14:18
1

If you don't care about allocation and performance isn't a huge concern, you can do something like:

let vals = if start < end {
    (start..end).collect::<Vec<_>>()
} else {
    (end..start).rev().collect::<Vec<_>>()
};
for i in vals {
    ...
}

Obviously this isn't ideal since you're allocating all those numbers, but it's a quick/dirty solution that might work in some cases.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.