Receive the success status of `push!(Set, element)`

It’s worth pointing out that in! gives the opposite status of what you want: in! is true if the element already existed in the set and no change occurred, while push_and_get_status! is true if the element is new and changed the set (well, your initial post’s version always changed the set, but you said that was not ideal so NonDairyNeutrino made it conditional). Therefore, you want the function composition !in!.

Search the name on the page and it’s there among a lot of other set operations Base.in!. Of course the name would be far easier to discover if there were more links from suggestions in other docstrings, especially from in, push!, Set. I evidently didn’t find it on the page either, mostly because I wrongly expected anything like it to also be implemented for dictionaries; in actuality, in! was only implemented for sets precisely because of the extra factor of a paired value.

I also checked the implementation, the Set method uses internals to avoid redundancy, the fallback AbstractSet method has the redundancy and looks pretty much like NonDairyNeutrino’s method but with true/false swapped.

2 Likes

That was because I forget about the method. I was vague.
The real intention is explained in my #20 post.

in! requires julia 1.11 or greater. This is not a solution for the
LTS version of julia at 1.10.x

TIL about in!. From the docstring:

in!(x, s::AbstractSet) -> Bool

If x is in s, return true. If not, push x into s and return false. This is equivalent to in(x, s) ? true : (push!(s, x); false), but may have a more efficient implementation.

Such a good idea someone already had it! :slight_smile:

You can use Base.in!. It was private in 1.10. Since it’s become public from 1.11 onwards, there is no risk of using it (it’s very very improbable it’ll be deleted in a patch release of 1.10)

1 Like