How to only read (first or last better) element of Set?

How to only read (first or last better) element of Set ?

 julia> X=Set(["a","b"])
Set(["b", "a"])

julia> X[1]
ERROR: MethodError: no method matching getindex(::Set{String}, ::Int64)
[1] top-level scope at none:0

julia> X(1)
ERROR: MethodError: objects of type Set{String} are not callable
[1] top-level scope at none:0

julia> pop(X)
ERROR: UndefVarError: pop not defined
[1] top-level scope at none:0

julia> pop!(X)
julia> X

Sets are unordered so what is the first or last element?

1 Like
julia> first(Set([1, 2]))

This gives the “first element” according to iteration order (which is not insertion order nor sorted order, at least for Base.Set).

I mean the one that returns the pop function! . Before pop! I want to know what is there

The current implementation of pop! and first for Set make them return the same element, and I don’t think this will change anytime soon. But this is not guarranteed in general for AbstractSet.


What do you think about collect(Set)[1] ?

EDIT: sorry, I didn’t see the collect in your example, my answer below is for indexing into a Set directly. Using collect(set)[1] works but is awfully inefficient, it has to iterate through all the set, just to return the first element.

It doesn’t work, and won’t be made to work: the indexing operation is meant to be fast, and a Set can’t generally be indexed fast. We can’t support only s[1] (for first) and not s[n] for any n.

AFAIK there is no exposed API for Set that allows this, as it is not an ordered collection. An implementation of pop! that picks a random element would be conforming.

It is very likely that you want to use (ie convert to) something else, but without some context it is not possible to give more specific advice.

1 Like