Why does delete!() work with sets, but not deleteat!()

If I had the following set:

numbers = Set([1,2,3,4,5])

and I do:

 delete!(3)

It will remove the number 3 from the Set, but when I use deleteat!(3) it throws an error, why?

Sets aren’t ordered, so deleting the third element has an undefined meaning.

3 Likes

When I provide 3, it isn’t the index of 3 but the element 3, correct? delete!() checked if the element existed first and then removed it?

delete(x) looks for the element x and deletes it. deleteat!(y) looks for the index y and deletes that index and whatever is in it.

5 Likes

Is this also why pop!() will return the first element of a Set and Dict?

It is not defined which is the element returned by pop!(set), the function documentation says:

pop!(collection) → item

Remove an item in collection and return it. If collection is an ordered container, the last item is returned.

Sets are not ordered so it is just defined an element will be removed and returned, not which one. The same applies to Dict that is also not an ordered container.

2 Likes

To me it seems strange that pop!(::Set) is even supported. pop!(::Set, x) and pop!(::Set, x, default), sure, but IMO pop!(::Set) would be better as a MethodError.

4 Likes

I kind of like being able to get arbitrary elements from a set. There are a lot of graph appropriate, where your need to iterate over everything, but it doesn’t really matter how.

4 Likes

I agree with Oscar in this one. It is a strange, but valid way of emptying a container one-by-one in the most efficient way. While this is not guaranteed, it seems clear to me that the item removed is the first in the data structure internal layout and, therefore, the easiest arbitrary element to remove (does not need a search).

2 Likes

I can see that. I wonder, though, if we should explicitly spell out the converse in the docstring:

  pop!(collection) -> item

  Remove an item in collection and return it. If collection is an ordered container, the last item is returned.

and add “; for unordered containers, an arbitrary element is returned.”

7 Likes

Create a PR with @tim.holy suggestion here.

3 Likes