From a9ab17f6706226fad41e0d02ac325ce35a353fd7 Mon Sep 17 00:00:00 2001 From: Colin Caine Date: Sat, 26 Aug 2023 21:49:21 +0100 Subject: [PATCH] Fix MutableBinaryHeap{T} when T is Union/abstract Each MutableBinaryHeapNode needs to be fully parameterised or Julia will throw a conversion error when trying to add them to MutableBinaryHeap's nodes field. --- src/heaps/mutable_binary_heap.jl | 4 ++-- test/test_mutable_binheap.jl | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/heaps/mutable_binary_heap.jl b/src/heaps/mutable_binary_heap.jl index 699aa538c..c2b809cd2 100644 --- a/src/heaps/mutable_binary_heap.jl +++ b/src/heaps/mutable_binary_heap.jl @@ -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 @@ -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 diff --git a/test/test_mutable_binheap.jl b/test/test_mutable_binheap.jl index e12c12313..1ad4bd7b7 100644 --- a/test/test_mutable_binheap.jl +++ b/test/test_mutable_binheap.jl @@ -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