Skip to content

Commit f5c2614

Browse files
authored
Merge pull request #627 from JuliaCollections/robindict_merge
Add merge function to RobinDict
2 parents 7ef51a5 + ea48409 commit f5c2614

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/robin_dict.jl

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Base: setindex!, sizehint!, empty!, isempty, length, copy, empty,
2-
getindex, getkey, haskey, iterate, @propagate_inbounds,
2+
getindex, getkey, haskey, iterate, @propagate_inbounds, merge,
33
pop!, delete!, get, get!, isbitstype, in, hashindex, isbitsunion,
44
isiterable, dict_with_eltype, KeySet, Callable, _tablesz, filter!
55

@@ -610,3 +610,22 @@ end
610610
@propagate_inbounds iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i))
611611

612612
filter!(f, d::RobinDict) = Base.filter_in_one_pass!(f, d)
613+
614+
function _merge_kvtypes(d, others...)
615+
K, V = keytype(d), valtype(d)
616+
for other in others
617+
K = promote_type(K, keytype(other))
618+
V = promote_type(V, valtype(other))
619+
end
620+
return (K, V)
621+
end
622+
623+
function merge(d::RobinDict, others::AbstractDict...)
624+
K, V = _merge_kvtypes(d, others...)
625+
merge!(RobinDict{K,V}(), d, others...)
626+
end
627+
628+
function merge(combine::Function, d::RobinDict, others::AbstractDict...)
629+
K, V = _merge_kvtypes(d, others...)
630+
merge!(combine, RobinDict{K,V}(), d, others...)
631+
end

test/test_robin_dict.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,28 @@ end
359359
@test h.idxfloor == get_idxfloor(h) == 0
360360
end
361361

362+
@testset "merge" begin
363+
h1 = RobinDict("a" => 1, "b" => 2)
364+
h2 = RobinDict("c" => 3, "d" => 4)
365+
d = merge(h1, h2)
366+
@test isa(d, RobinDict{String, Int})
367+
@test length(d) == 4
368+
@test d["a"] == 1
369+
@test d["b"] == 2
370+
@test d["c"] == 3
371+
@test d["d"] == 4
372+
end
373+
374+
@testset "merge with combine function" begin
375+
h1 = RobinDict("a" => 1, "b" => 2)
376+
h2 = RobinDict("b" => 3, "c" => 4)
377+
d = merge(+, h1, h2)
378+
@test isa(d, RobinDict{String, Int})
379+
@test d["b"] == 5
380+
@test d["a"] == 1
381+
@test d["c"] == 4
382+
end
383+
362384
@testset "invariants" begin
363385
h1 = RobinDict{Int, Int}()
364386
for i in 1:300

0 commit comments

Comments
 (0)