Skip to content

Commit 99faf1c

Browse files
authored
Recommend to use tuples to scalarize items in broadcast expressions (#35591)
* don't wrap `UInt8` in a tuple * Recommend to use tuples to scalarize an item. * Don't recommend to use Ref for scalarizing * Update arrays.md * Update refpointer.jl * add Matt's recommendation * remove whitespace
1 parent 8b010b5 commit 99faf1c

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

base/refpointer.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ There is no invalid (NULL) `Ref` in Julia, but a `C_NULL` instance of `Ptr` can
2020
a `ccall` Ref argument.
2121
2222
# Use in broadcasting
23+
`Ref` is sometimes used in broadcasting in order to treat the referenced values as a scalar:
2324
24-
Broadcasting with `Ref(x)` treats `x` as a scalar:
2525
```jldoctest
2626
julia> isa.(Ref([1,2,3]), [Array, Dict, Int])
2727
3-element BitArray{1}:

doc/src/manual/arrays.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -933,7 +933,7 @@ julia> convert.(Float32, [1, 2])
933933
1.0
934934
2.0
935935
936-
julia> ceil.((UInt8,), [1.2 3.4; 5.6 6.7])
936+
julia> ceil.(UInt8, [1.2 3.4; 5.6 6.7])
937937
2×2 Array{UInt8,2}:
938938
0x02 0x04
939939
0x06 0x07
@@ -945,6 +945,17 @@ julia> string.(1:3, ". ", ["First", "Second", "Third"])
945945
"3. Third"
946946
```
947947

948+
Sometimes, you want a container (like an array) that would normally participate in broadcast to be "protected"
949+
from broadcast's behavior of iterating over all of its elements. By placing it inside another container
950+
(like a single element [`Tuple`](@ref)) broadcast will treat it as a single value.
951+
```jldoctest
952+
julia> ([1, 2, 3], [4, 5, 6]) .+ ([1, 2, 3],)
953+
([2, 4, 6], [5, 7, 9])
954+
955+
julia> ([1, 2, 3], [4, 5, 6]) .+ tuple([1, 2, 3])
956+
([2, 4, 6], [5, 7, 9])
957+
```
958+
948959
## Implementation
949960

950961
The base array type in Julia is the abstract type [`AbstractArray{T,N}`](@ref). It is parameterized by

0 commit comments

Comments
 (0)