Is `Range::partition_point` a good idea?

Binary search isn't just for arrays, right? But all the binary search-related methods in libstd are attached to [T].

Scale of 1 to 10, how std-worthy is this idea:

    // Use binary search to find the inverse of a monotonic function
    (1..100_000).partition_point(|t| population_at(t) < n)

    // Use binary search to find the point in a log file corresponding to a time t
    (0..record_count).partition_point(|i| buffered_log_reader.get(i).timestamp < t)

    // Say you have some data that goes up and then down again. Find the peak.
    (0..data.len() - 1).partition_point(|i| data[i] < data[i + 1])

In general, this would be useful for binary search any time the data you're searching isn't stored as elements in a literal vector/array. Data can be elsewhere — in a file on disk; on a server you need to query; in some other data structure; or it could be something you compute, and don't want to compute for all possible i.

This would be a new inherent method on ranges:

// in std::ops

impl<T: Step> Range<T> {
    /// Finds the partition point of a predicate in a range by binary search.
    /// Like `[T]::partition_point` but without the slice.
    pub fn partition_point<F: Fn(T) -> bool>(&self, test: F) -> T
    { ... }
}

Implementation sketch, in the playground

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.