Skip to content

Commit

Permalink
add method to reduce, specialized for merge (#21672)
Browse files Browse the repository at this point in the history
  • Loading branch information
jlapeyre committed May 23, 2018
1 parent 46dcb35 commit 6b575f2
Show file tree
Hide file tree
Showing 2 changed files with 22 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 @@ -684,6 +684,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!, Dict{K,V}(), items)
end

struct ImmutableDict{K,V} <: AbstractDict{K,V}
parent::ImmutableDict{K,V}
key::K
Expand Down
16 changes: 16 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,22 @@ end
@test d1 == Dict("A" => 1, "B" => 15, "C" => 28)
end

@testset "Dict reduce merge" begin
f = (i::Vector{<:Dict}, o) -> begin
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
f([Dict(1=>2), Dict(1.0=>2.0)], Dict(1.0=>2.0))
f([Dict(1=>2), Dict(2=>Complex(1.0, 1.0))], Dict(2=>Complex(1.0, 1.0), 1=>Complex(2.0, 0.0)))
f([Dict(1=>2), Dict(3=>4)], Dict(3=>4, 1=>2))
f([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 6b575f2

Please sign in to comment.