I am looking for a bisect operation in Haskell similar to Python’s bisect_left() and friends. The input would be a lower bound, an upper bound, a non-decreasing function (Ord a)=>(Int->a) which must be defined for all integers between the lower and upper bound, and a search value. The return value is the highest integer i where lower <= i <= upper and f(i) < search_term. Performance should be O(log(n)).
Hoogling for this:
(Ord a)=>(Int->a)->Int->Int->a->Int
does not yield any results.
Is there a standard, generic binary search operator in a library somewhere?
Ross Paterson’s binary-search package on Hackage does what you’re looking for. Specifically, see searchFromTo, which has type signature
As Tikhon points out,
[a]in Haskell is a linked list rather than an array. Since linked lists only support sequential access, it is not possible to get a logarithmic-time search on an[a]data structure. Instead, you should use a genuine array data structure — see the vector library for the preferred implementation of arrays.Dan Doel has written a family of binary search functions for the mutable vectors in the vector package: see Data.Vector.Algorithms.Search in his vector-algorithms library. In contrast to Ross Paterson’s library, which provides a pure API, the API in
Data.Vector.Algorithms.Searchis monadic (that is, it must be run in theSTmonad or theIOmonad).