leanprover / leanprover/lean4

RFC: Generalize Array.binSearch with partition-point-style API

Open
#14,931 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

RFC
Dominant language
Lean
Stars
9.2k
Forks
990
Avg merge
1d 17h
Merged PRs (30d)
175

Description

Proposal

The "partition point" in the title comes from Rust's slice.partition_point. In short, given a unary boolean predicate f, this function finds the first index i in an array as where f(as[0]), ..., f(as[i-1]) are true and f(as[i]), ... are false.

This is best expressed by the following signature:

def partitionPoint {n : Nat} (f : Fin n -> Bool) : Fin (n + 1)

This function can act as a building block for implementing binSearch, but it is also useful for other uses involving (parametric) binary search as well, such as implementing mathematical functions, say Nat.isqrt.

Also, as far as I can tell, the current binSearch does not specify which element is chosen if multiple items in as are equal. A partitionPoint-based implementation guarantees that the leftmost one will be chosen.

Proposed APIs:

def partitionPoint {n : Nat} (f : Fin n → Bool) : Fin (n + 1)
def Vector.partitionPoint {α : Type u} {n : Nat} (vec : Vector α n) (pred : α → Bool) : Fin (n + 1)
def Array.partitionPoint {α : Type u} (as : Array α) (pred : α → Bool) : Fin (as.size + 1)
-- reimplementations of five functions in Init.Data.Array.BinSearch
def Nat.partitionPoint (pred : Nat → Bool) (lo : Nat) (hi : Nat) : Nat
def Int.partitionPoint (pred : Int → Bool) (lo : Int) (hi : Int) : Int

example implementation.

Community Feedback

Zulip thread

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Init.Data.Array.BinSearch and the linked example implementation. Compare the current binSearch behavior with the proposed partitionPoint APIs, including duplicate handling and the Nat and Int variants. Done means the API design is agreed and the required generalizations are implemented consistently.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.