Skip to content

Commit 6deeec4

Browse files
authored
Add note about broadcasting etc. to the readme (#154)
* add note about broadcasting etc. to readme * upgrade to warning * syntax colour * tweak * tweak
1 parent 4ed6433 commit 6deeec4

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,38 @@ These types have methods that perform many operations efficiently,
8787
including elementary algebra operations like multiplication and addition,
8888
as well as linear algebra methods like
8989
`norm`, `adjoint`, `transpose` and `vec`.
90+
91+
## Warning!
92+
93+
Broadcasting operations and `map`, `mapreduce` are also done efficiently, by evaluating the function being applied only once:
94+
95+
```julia
96+
julia> map(sqrt, Fill(4, 2,5)) # one evaluation, not 10, to save time
97+
2×5 Fill{Float64}: entries equal to 2.0
98+
99+
julia> println.(Fill(pi, 10))
100+
π
101+
10-element Fill{Nothing}: entries equal to nothing
102+
```
103+
104+
Notice that this will only match the behaviour of a dense matrix from `fill` if the function is pure. And that this shortcut is taken *before* any other fused broadcast:
105+
106+
```julia
107+
julia> map(_ -> rand(), Fill("pi", 2,5)) # not a pure function!
108+
2×5 Fill{Float64}: entries equal to 0.7201617100284206
109+
110+
julia> map(_ -> rand(), fill("4", 2,5)) # 10 evaluations, different answer!
111+
2×5 Matrix{Float64}:
112+
0.43675 0.270809 0.56536 0.0948089 0.24655
113+
0.959363 0.79598 0.238662 0.401909 0.317716
114+
115+
julia> ones(1,5) .+ (_ -> rand()).(Fill("vec", 2)) # Fill broadcast is done first
116+
2×5 Matrix{Float64}:
117+
1.51796 1.51796 1.51796 1.51796 1.51796
118+
1.51796 1.51796 1.51796 1.51796 1.51796
119+
120+
julia> ones(1,5) .+ (_ -> rand()).(fill("vec", 2)) # fused, 10 evaluations
121+
2×5 Matrix{Float64}:
122+
1.51337 1.17578 1.19815 1.43035 1.2987
123+
1.30253 1.21909 1.61755 1.02645 1.77681
124+
```

0 commit comments

Comments
 (0)