I'd like to be able to create a Range
and then test if a variable is contained in that range. Something that looks like this:
fn main() {
let a = 3..5;
assert!(a.contains(4));
}
Right now, the only obvious thing I see is to use Iterator::any
. This is ugly because it would take an O(1) operation and make it O(n):
fn main() {
let mut a = 3..5;
assert!(a.any(|v: i32| v == 4));
}
This can be done using the lower_bound function. If there is any value which is equal to the query, then the number overlaps the range. If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2. If it is hashed as 1, then the number does not overlaps, else it does overlap.
between() function in R Language is used to check that whether a numeric value falls in a specific range or not. A lower bound and an upper bound is specified and checked if the value falls in it.
You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.
As with ValueRange's of() method, we passed lowerBound and upperBound to Range's static between() method to create Range objects. We then used the contains() method to check whether number existed within each object's range.
As of Rust 1.35, the original code will almost1 compile as-is using Range::contains
:
fn main() { let a = 3..5; assert!(a.contains(&4)); }
1 Passing &4
instead of 4
to contains()
.
There is nothing on Range
itself (at present, anyway), but it is not difficult to do this; after all, it just takes a couple of comparisons:
4 >= a.start && 4 < a.end
You can use match
too:
fn main() {
let v = 132;
match v {
1...100 => println!("Inside"),
_ => println!("Outside")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With