Skip to content

Commit

Permalink
Fix MutableBinaryHeap{T} when T is Union/abstract
Browse files Browse the repository at this point in the history
Each MutableBinaryHeapNode needs to be fully parameterised or Julia will
throw a conversion error when trying to add them to MutableBinaryHeap's
nodes field.
  • Loading branch information
cmcaine committed Aug 26, 2023
1 parent c4b8b5f commit a9ab17f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/heaps/mutable_binary_heap.jl
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ function Base.push!(h::MutableBinaryHeap{T}, v) where T
nodemap = h.node_map
i = length(nodemap) + 1
nd_id = length(nodes) + 1
push!(nodes, MutableBinaryHeapNode(convert(T, v), i))
push!(nodes, MutableBinaryHeapNode{T}(convert(T, v), i))
push!(nodemap, nd_id)
_heap_bubble_up!(h.ordering, nodes, nodemap, nd_id)
return i
Expand Down Expand Up @@ -260,7 +260,7 @@ function update!(h::MutableBinaryHeap{T}, i::Int, v) where T
nd_id = nodemap[i]
v0 = nodes[nd_id].value
x = convert(T, v)
nodes[nd_id] = MutableBinaryHeapNode(x, i)
nodes[nd_id] = MutableBinaryHeapNode{T}(x, i)
if Base.lt(ordering, x, v0)
_heap_bubble_up!(ordering, nodes, nodemap, nd_id)
else
Expand Down
10 changes: 10 additions & 0 deletions test/test_mutable_binheap.jl
Original file line number Diff line number Diff line change
Expand Up @@ -342,4 +342,14 @@ end
update!(h, 2, 20)
@test isequal(heap_values(h), [0.5, 10.1, 3.0, 20.0])
end

@testset "T is a Union" begin
h = MutableBinaryMinHeap{Union{Int, Float64}}()
push!(h, 1)
push!(h, 2.0)
update!(h, 1, 1.5)
update!(h, 2, 3)
@test pop!(h) === 1.5
@test pop!(h) === 3
end
end # @testset MutableBinheap

0 comments on commit a9ab17f

Please sign in to comment.