Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add replace methods for Tuple #38216

Merged
merged 2 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions base/set.jl
Original file line number Diff line number Diff line change
Expand Up @@ -728,3 +728,30 @@ function _replace!(new::Callable, t::Set{T}, ::AbstractSet, count::Int) where {T
end
t
end

### replace for tuples

function _replace(f::Callable, t::Tuple, count::Int)
if count == 0 || isempty(t)
t
else
x = f(t[1])
(x, _replace(f, tail(t), count - !==(x, t[1]))...)
end
end

replace(f::Callable, t::Tuple; count::Integer=typemax(Int)) =
_replace(f, t, check_count(count))

function _replace(t::Tuple, count::Int, old_new::Tuple{Vararg{Pair}})
_replace(t, count) do x
@_inline_meta
for o_n in old_new
isequal(first(o_n), x) && return last(o_n)
end
return x
end
end

replace(t::Tuple, old_new::Pair...; count::Integer=typemax(Int)) =
_replace(t, check_count(count), old_new)
6 changes: 6 additions & 0 deletions test/sets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -586,11 +586,14 @@ end
@testset "replace! & replace" begin
a = [1, 2, 3, 1]
@test replace(x -> iseven(x) ? 2x : x, a) == [1, 4, 3, 1]
@test replace(x -> iseven(x) ? 2x : x, Tuple(a)) === (1, 4, 3, 1)
@test replace!(x -> iseven(x) ? 2x : x, a) === a
@test a == [1, 4, 3, 1]
@test replace(a, 1=>0) == [0, 4, 3, 0]
@test replace(Tuple(a), 1=>0) === (0, 4, 3, 0)
for count = (1, 0x1, big(1))
@test replace(a, 1=>0, count=count) == [0, 4, 3, 1]
@test replace(Tuple(a), 1=>0, count=count) === (0, 4, 3, 1)
end
@test replace!(a, 1=>2) === a
@test a == [2, 4, 3, 2]
Expand All @@ -615,6 +618,7 @@ end

for count = (0, 0x0, big(0)) # count == 0 --> no replacements
@test replace([1, 2], 1=>0, 2=>0; count) == [1, 2]
@test replace((1, 2), 1=>0, 2=>0; count) === (1, 2)
for dict = (Dict(1=>2, 2=>3), IdDict(1=>2, 2=>3))
@test replace(dict, (1=>2) => (1=>3); count) == dict
end
Expand Down Expand Up @@ -668,7 +672,9 @@ end

# test that isequal is used
@test replace([NaN, 1.0], NaN=>0.0) == [0.0, 1.0]
@test replace((NaN, 1.0), NaN=>0.0) === (0.0, 1.0)
@test replace([1, missing], missing=>0) == [1, 0]
@test replace((1, missing), missing=>0) === (1, 0)
end

@testset "⊆, ⊊, ⊈, ⊇, ⊋, ⊉, <, <=, issetequal" begin
Expand Down