Queue/Definition: Difference between revisions
Content added Content deleted
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: | 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". |
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> |
<lang Julia> |
||
struct Queue{T} |
|||
a::Array{T,1} |
a::Array{T,1} |
||
end |
end |
||
Line 3,807: | Line 3,807: | ||
Base.isempty(q::Queue) = isempty(q.a) |
Base.isempty(q::Queue) = isempty(q.a) |
||
function Base.pop! |
function Base.pop!(q::Queue{T}) where {T} |
||
!isempty(q) || error("queue must be non-empty") |
!isempty(q) || error("queue must be non-empty") |
||
pop!(q.a) |
pop!(q.a) |
||
end |
end |
||
function Base.push! |
function Base.push!(q::Queue{T}, x::T) where {T} |
||
pushfirst!(q.a, x) |
|||
return q |
return q |
||
end |
end |
||
function Base.push! |
function Base.push!(q::Queue{Any}, x::T) where {T} |
||
pushfirst!(q.a, x) |
|||
return q |
return q |
||
end |
end |
||
Line 3,828: | Line 3,828: | ||
<pre> |
<pre> |
||
julia> q = Queue() |
julia> q = Queue() |
||
Queue{Any}( |
Queue{Any}(Any[]) |
||
julia> isempty(q) |
julia> isempty(q) |
||
Line 3,834: | Line 3,834: | ||
julia> push!(q, 1) |
julia> push!(q, 1) |
||
Queue{Any}( |
Queue{Any}(Any[1]) |
||
julia> isempty(q) |
julia> isempty(q) |
||
Line 3,840: | Line 3,840: | ||
julia> push!(q, "two") |
julia> push!(q, "two") |
||
Queue{Any}( |
Queue{Any}(Any["two",1]) |
||
julia> push!(q, 3.0) |
julia> push!(q, 3.0) |
||
Queue{Any}( |
Queue{Any}(Any[3.0,"two",1]) |
||
julia> push!(q, false) |
julia> push!(q, false) |
||
Queue{Any}( |
Queue{Any}(Any[false,3.0,"two",1]) |
||
julia> pop!(q) |
julia> pop!(q) |
||
Line 3,862: | Line 3,862: | ||
julia> pop!(q) |
julia> pop!(q) |
||
ERROR: queue must be non-empty |
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> |
</pre> |
||