diff --git a/NEWS.md b/NEWS.md index d13aa9dfc016b..0bbd2c540b82c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -46,6 +46,7 @@ Standard library changes Previously, the functions `+`, `-`, `*`, `/`, `conj`, `real` and `imag` returned the unwrapped element when operating over zero-dimensional arrays ([#32122]). * `IPAddr` subtypes now behave like scalars when used in broadcasting ([#32133]). +* `Pair` is now treated as a scalar for broadcasting ([#32209]). * `clamp` can now handle missing values ([#31066]). * `empty` now accepts a `NamedTuple` ([#32534]). * `mod` now accepts a unit range as the second argument to easily perform offset modular arithmetic to ensure the result is inside the range ([#32628]). diff --git a/base/broadcast.jl b/base/broadcast.jl index 206e2e2da7042..743568845cae1 100644 --- a/base/broadcast.jl +++ b/base/broadcast.jl @@ -652,7 +652,7 @@ julia> Broadcast.broadcastable("hello") # Strings break convention of matching i Base.RefValue{String}("hello") ``` """ -broadcastable(x::Union{Symbol,AbstractString,Function,UndefInitializer,Nothing,RoundingMode,Missing,Val,Ptr,Regex}) = Ref(x) +broadcastable(x::Union{Symbol,AbstractString,Function,UndefInitializer,Nothing,RoundingMode,Missing,Val,Ptr,Regex,Pair}) = Ref(x) broadcastable(::Type{T}) where {T} = Ref{Type{T}}(T) broadcastable(x::Union{AbstractArray,Number,Ref,Tuple,Broadcasted}) = x # Default to collecting iterables — which will error for non-iterables diff --git a/base/pair.jl b/base/pair.jl index a059a55b765a8..3ce88177787cc 100644 --- a/base/pair.jl +++ b/base/pair.jl @@ -21,7 +21,7 @@ const => = Pair Construct a `Pair` object with type `Pair{typeof(x), typeof(y)}`. The elements are stored in the fields `first` and `second`. They can also be accessed via -iteration. +iteration (but a `Pair` is treated as a single "scalar" for broadcasting operations). See also: [`Dict`](@ref) diff --git a/test/broadcast.jl b/test/broadcast.jl index 32a0676d6b11d..a2289d684735f 100644 --- a/test/broadcast.jl +++ b/test/broadcast.jl @@ -831,3 +831,7 @@ let a = rand(5), b = rand(5), c = copy(a) x[[1,1]] .+= 1 @test x == [2] end + +# treat Pair as scalar: +@test replace.(split("The quick brown fox jumps over the lazy dog"), r"[aeiou]"i => "_") == + ["Th_", "q__ck", "br_wn", "f_x", "j_mps", "_v_r", "th_", "l_zy", "d_g"]