DataStructures.jl icon indicating copy to clipboard operation
DataStructures.jl copied to clipboard

Support `pushfirst!` and `popfirst!` for ordered collections

Open omus opened this issue 7 years ago • 3 comments

It would be nice to have these for OrderedDict and OrderedSet. At the moment in Julia 0.7:

julia> using DataStructures

julia> o = OrderedSet([1,2,3])
OrderedSet{Int64}([1, 2, 3])

julia> push!(o, 4)
OrderedSet{Int64}([1, 2, 3, 4])

julia> pop!(o, 4)
4

julia> pushfirst!(o, 0)
ERROR: MethodError: no method matching pushfirst!(::OrderedSet{Int64}, ::Int64)
Closest candidates are:
  pushfirst!(::Any, ::Any, ::Any) at abstractarray.jl:2040
  pushfirst!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2041
  pushfirst!(::Array{T,1}, ::Any) where T at array.jl:1063
  ...
Stacktrace:
 [1] top-level scope at none:0

julia> popfirst!(o)
ERROR: MethodError: no method matching popfirst!(::OrderedSet{Int64})
Closest candidates are:
  popfirst!(::DataStructures.IntSet) at /Users/omus/.julia/packages/DataStructures/eUHI/src/int_set.jl:90
  popfirst!(::BitSet) at bitset.jl:255
  popfirst!(::BitArray{1}) at bitarray.jl:817
  ...
Stacktrace:
 [1] top-level scope at none:0

omus avatar Jul 21 '18 00:07 omus

Has this proposition been adressed?

It seems that by now (v0.8), the pop!(ss) method allows to pop the first element in a SortedSet, but apparently there is no equivalent method for SortedDict, where the item with the smallest key would be popped.

What is the most efficitent way to do this at the moment ?

SimonCoste avatar Feb 24 '21 16:02 SimonCoste

I suggest startof followed by deref followed by delete! If you don't actually need the first item and you are using pop merely to discard it, then delete!((sd, startof(sd))) should suffice.

StephenVavasis avatar Feb 24 '21 17:02 StephenVavasis

Stephen, thank you! A simple pop!(SortedDict) would be natural and welcome in the future.

SimonCoste avatar Feb 24 '21 17:02 SimonCoste