Description
I have never used sort.Search
to build a sorted list (slice). It's too expensive and there are better ways. However, I use it often to do what its name suggests: search.
The API is designed for the growth case, which is fine and general, but the general (growth) case is rare, perhaps very rare, and handling the return value is clumsy†.
I suggest adding another function, say sort.Contains
, that just says yes or no to the question of presence of the element. Here is sort.Search's use for the pure search case, right from the documentation:
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i < len(data) && data[i] == x {
// x is present at data[i]
} else {
// x is not present in data,
// but i is the index where it would be inserted.
}
Besides the messy handling, that extra comparison has always bothered me.
Here is what that would look like with the proposed function:
if sort.Contains(len(data), func(i int) bool { return data[i] >= x }) {
// x is present at data[i]
}
This seems so much more intuitive and semantically lightweight. If you needed the index - but why would you if you weren't going to insert there? - you could go back to the existing Search
function.
It should be very simple to implement by having both Search
and Contains
call a helper that reports presence, and returning the appropriate result, or by just writing Contains
itself - like Search
, it's very short.
I already filled in the proposal questionnaire here: #45624
† And poorly documented, but that is fixable.