Skip to content

Commit

Permalink
Add methods to reduce, specialized for merge on vector of Dict (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jlapeyre authored and nalimilan committed Apr 4, 2019
1 parent ce17e05 commit 4105848
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,12 @@ end

filter!(f, d::Dict) = filter_in_one_pass!(f, d)

function reduce(::typeof(merge), items::Vector{<:Dict})
K = mapreduce(keytype, promote_type, items)
V = mapreduce(valtype, promote_type, items)
return reduce(merge!, items; init=Dict{K,V}())
end

function map!(f, iter::ValueIterator{<:Dict})
dict = iter.dict
vals = dict.vals
Expand Down
17 changes: 17 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,23 @@ end
@test d1 == Dict("A" => 1, "B" => 15, "C" => 28)
end

@testset "Dict reduce merge" begin
function check_merge(i::Vector{<:Dict}, o)
r1 = reduce(merge, i)
r2 = merge(i...)
t = typeof(o)
@test r1 == o
@test r2 == o
@test typeof(r1) == t
@test typeof(r2) == t
end
check_merge([Dict(1=>2), Dict(1.0=>2.0)], Dict(1.0=>2.0))
check_merge([Dict(1=>2), Dict(2=>Complex(1.0, 1.0))],
Dict(2=>Complex(1.0, 1.0), 1=>Complex(2.0, 0.0)))
check_merge([Dict(1=>2), Dict(3=>4)], Dict(3=>4, 1=>2))
check_merge([Dict(3=>4), Dict(:a=>5)], Dict(:a => 5, 3 => 4))
end

@testset "misc error/io" begin
d = Dict('a'=>1, 'b'=>1, 'c'=> 3)
@test_throws ErrorException 'a' in d
Expand Down

0 comments on commit 4105848

Please sign in to comment.