From ea3ca3b8b8bb317dba7e4b5b2b660cf7bd947776 Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Fri, 31 May 2019 12:55:21 -0400 Subject: [PATCH] treat Pair as broadcast scalar --- NEWS.md | 1 + base/broadcast.jl | 2 +- base/pair.jl | 2 +- test/broadcast.jl | 4 ++++ 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 599ab62744ea9..fb7cd35a06f9f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -33,6 +33,7 @@ Standard library changes (environment, flags, working directory, etc) if `x` is the first interpolant and errors otherwise ([#24353]). * `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]). #### Libdl diff --git a/base/broadcast.jl b/base/broadcast.jl index 4d5ca6b92fe19..2ff4e04dfc7b3 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 5ee56cf94fe87..cab66a1534b4b 100644 --- a/test/broadcast.jl +++ b/test/broadcast.jl @@ -822,3 +822,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"]