Queue/Definition: Difference between revisions

Update code for recent versions of Julia
m (correction: don't implement a stack, implement a First In First Out (FIFO) Queue - pop is actually PULL FIRST)
(Update code for recent versions of Julia)
Line 3,797:
Julia provides a variety of queue-like methods for vectors, making the solution to this task rather straightforward. Define a <tt>Queue</tt> in terms of a one dimensional array, and provide its methods using the appropriate vector operations. To adhere to Julia naming conventions, the queue operations are named "push!", "pop!" and "isempty" rather than "push", "pop" and "empty".
<lang Julia>
typestruct Queue{T}
a::Array{T,1}
end
Line 3,807:
Base.isempty(q::Queue) = isempty(q.a)
 
function Base.pop!{T}(q::Queue{T}) where {T}
!isempty(q) || error("queue must be non-empty")
pop!(q.a)
end
 
function Base.push!{T}(q::Queue{T}, x::T) where {T}
unshiftpushfirst!(q.a, x)
return q
end
 
function Base.push!{T}(q::Queue{Any}, x::T) where {T}
unshiftpushfirst!(q.a, x)
return q
end
Line 3,828:
<pre>
julia> q = Queue()
Queue{Any}({}Any[])
 
julia> isempty(q)
Line 3,834:
 
julia> push!(q, 1)
Queue{Any}({Any[1}])
 
julia> isempty(q)
Line 3,840:
 
julia> push!(q, "two")
Queue{Any}({Any["two",1}])
 
julia> push!(q, 3.0)
Queue{Any}({Any[3.0,"two",1}])
 
julia> push!(q, false)
Queue{Any}({Any[false,3.0,"two",1}])
 
julia> pop!(q)
Line 3,862:
julia> pop!(q)
ERROR: queue must be non-empty
Stacktrace:
in pop! at none:2
[1] error(s::String)
@ Base ./error.jl:33
[2] pop!(q::Queue{Any})
@ Main /tmp/cmdline_1648668849_nacnudus/lines.jl:3
[3] top-level scope
@ REPL[11]:1
</pre>
 
Anonymous user