How to use `iterate(s::Stack)` and `Iterators.reverse(s::Stack{T})` for Stack and Queue in DataStructures.jl?

I am reading documentation for DataStructures.jl, namely this page: Stack and Queue · DataStructures.jl and cannot figure out how to use iterate(s::Stack) and Iterators.reverse(s::Stack{T})?

I try this:

s = Stack{Int}()
for i ∈ 1:5
    push!(s,i)
end

for i ∈ iterate(s)
    println(i)
end

and getting something that I don’t understand:

5
(DataStructures.DequeBlock{Int64}(capa = 1024, front = 1, back = 5): [1, 2, 3, 4, 5], 4)

How to iterate properly?

You don’t need iterate here:

julia> for i ∈ s
           println(i)
       end
5
4
3
2
1

julia> for i ∈ Iterators.reverse(s)
           println(i)
       end
1
2
3
4
5
for i ∈ Iterators.reverse(s)
    println(i)
end

gives an error

MethodError: no method matching iterate(::Base.Iterators.Reverse{Stack{Int64}})

What version of DataStructures.jl are you using? It looks like support for Iterators.reverse was added in version 0.18.4. You can find out what version you are running with ] st DataStructures in the REPL.

2 Likes

It seems strange to me that Stack would support Iterators.reverse, one of the defining characteristic of a Stack is only allowing access to the top element.

v0.17.20, Julia 1.5.3 How to update DataStructures to the latest in REPL? up DataStructures does not update it.

Most likely, that means some other package is holding it back (by having it as a dependency, restricted to v0.17). Can you try add DataStructures@0.18?

2 Likes

Thanks! It works. First it gave me the error: ERROR: Unsatisfiable requirements detected for package Lasso. I don’t need Lasso for now, so I removed it, then add DataStructures@0.18 updated it to v0.18.9