Hi, quick question:
Is there a “contains” builtin “in” for arrays/slices similar to maps and bit_set?
And if not, are there any reasons why not? ![]()
I couldn’t find anything in the forum, unfortunately.
Hi, quick question:
Is there a “contains” builtin “in” for arrays/slices similar to maps and bit_set?
And if not, are there any reasons why not? ![]()
I couldn’t find anything in the forum, unfortunately.
Not as a builtin, no. You can use slice.linear_search/slice.binary_search from core:slice, depending on whether the data is sorted.
bit_sets and maps work with in because they’re data structures made for look-ups and can do it efficiently, arrays generally can’t. The only reasonable way of searching an array without making assumptions would be a linear search, which is O(n) and can easily become very expensive if you’re doing it a lot on arrays of more than a few values. If you find yourself needing to do that a lot, it might be an indication that there’s a more suitable data structure.
On top of that, the values of an array/slice don’t need to be comparable.
Thank you for your quick response!
I use it mainly for small arrays (N<10) where the overhead of a hashing structure is probably higher than a linear search.
There are definitely use cases for linear searches, and it sounds like you have a good case for it. But they do need to be done with consideration, so the friction is intentional.