Pre-RFC: how do you like adding Range::contains(&A) -> bool?


#1

Isn’t it handy to have something like this?

impl<A: PartialOrd> Range {
  fn contains(&self, x: &A) -> bool {
    (*self.start <= *x) && (*x < *self.end)
  }
}

I also thought about a new operator overload if 10 <= 1..100 { ... } (mimicking ‘∈’) but it might not be a good idea.


#2

The correct name for this function would be .contains(_). And AFAIK, it’s already being considered.


#3

Thanks, corrected the title from include() to contains() though I never fully understood the third-person singular simple-present “s” used only for predicates…

Good to know someone already considered for it. Any pointers to the previous discussions would be appreciated.


#4

The third person makes a.contains(b) more natural to read.


#5

To me, a method without the “s” sounds like an imperative form, so it’d be funny for that to be a predicate. If I saw a method name .include(), I’d think that it either takes some value and includes that into the object, or includes the object to… somewhere else.

The RFC is here: https://github.com/rust-lang/rfcs/pull/1434


#6

Great, it was among RFC PRs…

So when I have a proposal on a new feature, I have to check for dup in

  1. rust-lang/rust PRs and issues
  2. Here (Internals Discourse)
  3. RFC repo https://github.com/rust-lang/rfcs/tree/master/text , and
  4. RFC PRs and issues

#7

Why not add it to all iterators?


#8

Perhaps any(|e| e == x) just suffices? And I want (...).contains(10) to immediately return true.


#9

I would expect contains to only be defined if it’s efficient. At least with any, you default to assuming 𝑶(𝒏) behaviour.


#10

I like the low level part of algorithms, and there only the programmer knows when it’s efficient.

Remember that linear search (here called “inefficient”) is the efficient thing to do when your dataset is small. For example, Rust’s BTreeMap uses linear search inside a node.