From 41058485fce3a8b2770dbc68379c49b90ccdc9c7 Mon Sep 17 00:00:00 2001 From: John Lapeyre Date: Thu, 4 Apr 2019 17:05:07 +0200 Subject: [PATCH] Add methods to `reduce`, specialized for `merge` on vector of Dict (#26440) --- base/dict.jl | 6 ++++++ test/dict.jl | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/base/dict.jl b/base/dict.jl index 9cd3fe5009de1..ab6e636397838 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -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 diff --git a/test/dict.jl b/test/dict.jl index fd691ce8a62b8..904cdb9526c57 100644 --- a/test/dict.jl +++ b/test/dict.jl @@ -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