Skip to content

Commit

Permalink
Add Experimental.mergewith!!
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Jan 13, 2020
1 parent 5610dee commit 327a0de
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 15 deletions.
1 change: 1 addition & 0 deletions src/BangBang.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ using .NoBang: Empty, ImmutableContainer, SingletonVector, singletonof
include("core.jl")
include("base.jl")
include("linearalgebra.jl")
include("experimental.jl")
include("initials.jl")
include("macro.jl")
include("dataframes_impl.jl")
Expand Down
18 changes: 3 additions & 15 deletions src/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -297,24 +297,12 @@ Dict{Symbol,Float64} with 1 entry:
:a => 1.5
```
"""
merge!!(dict::Union{AbstractDict,NamedTuple,Empty}, others...) =
merge!!(right, dict, others...)

merge!!(combine, dict, other) =
foldl(pairs(other); init=dict) do dict, (k, v2)
v1 = get(dict, k, _NoValue())
setindex!!(dict, v1 isa _NoValue ? v2 : combine(v1, v2), k)
end

merge!!(combine, dict, others...) =
foldl(others; init=dict) do dict, other
merge!!(combine, dict, other)
end
merge!!(dict, others...) = merge!!(right, dict, others...)
merge!!(combine::Base.Callable, dict, others...) =
Experimental.mergewith!!(combine, dict, others...)

right(_, x) = x

struct _NoValue end

#=
"""
splice!!(sequence, i, [replacement]) -> (sequence′, item)
Expand Down
37 changes: 37 additions & 0 deletions src/experimental.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module Experimental

export mergewith!!

using ..BangBang: setindex!!

struct _NoValue end

"""
mergewith!!(combine, dict, others...) -> dict′
mergewith!!(combine)
Like `merge!!(combine, dict, others...)` but `combine` does not have
to be a `Function`.
The curried form `mergewith!!(combine)` returns the function
`(args...) -> mergewith!!(combine, args...)`.
See also:
[Add mergewith[!](combine, dicts...) by tkf · Pull Request #34296 · JuliaLang/julia](https://github.com/JuliaLang/julia/pull/34296)
"""
mergewith!!

mergewith!!(combine, dict, other) =
foldl(pairs(other); init=dict) do dict, (k, v2)
v1 = get(dict, k, _NoValue())
setindex!!(dict, v1 isa _NoValue ? v2 : combine(v1, v2), k)
end

mergewith!!(combine, dict, others...) =
foldl(others; init=dict) do dict, other
mergewith!!(combine, dict, other)
end

mergewith!!(combine) = (args...) -> mergewith!!(combine, args...)

end # module

0 comments on commit 327a0de

Please sign in to comment.