Is a number in a range


#1

Hi, what would you find to be the most elegant way to check if a value is in a range?

match yearday {
    0...366 => {
    // do stuff here
    },
    _ => panic!
}

or

if let 0...366 = yearday {
// do stuff here
}

I see that the if let scenario is shorter, I just feel like it’s a misuse of the binding keyword let since there is no actual destructuring taking place.
Thanks


#2

There’s always the if 0 <= yearday && yearday <= 366 { ... } option too.


#3

There’s always the option of defining the functions or method’s you’d like to use to express yourself with.

trait Contains<T> {
    fn contains(&self, T) -> bool;
}

impl<T: PartialOrd> Contains<T> for Range<T> {
   fn contains(&self, elt: T) -> bool { self.start >= elt && elt < self.end }
}

if (0..366).contains(x) { ... }

#4

This solution was what I would have expected in the stdlib, but since it wasn’t there I asked here for the most common work around. :smiley: :+1:

Would this be enough for an RFC?


#5

this is awesome, and this feature has been added to nightly:
http://doc.rust-lang.org/nightly/std/ops/struct.Range.html#method.contains
http://doc.rust-lang.org/nightly/std/ops/enum.RangeInclusive.html#method.contains

There is a bug with the implementation posted here, should read self.start <= elt


#6

For dates the range should probably be inclusive at both ends, but for completeness you probably want four range objects for each kind of range [] (] [) (). It should probably be four range types and a single contains trait function as the inclusive/exclusiveness is a property of the range.