Skip to content

Commit b4b956a

Browse files
committed
Test associativity
1 parent ece81cf commit b4b956a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

test/broadcast.jl

+29
Original file line numberDiff line numberDiff line change
@@ -827,4 +827,33 @@ end
827827
bc = Broadcast.instantiate(Broadcast.broadcasted(*, xs2, ys2))
828828
@test IndexStyle(bc) == IndexCartesian()
829829
@test sum(bc) == mapreduce(Base.splat(*), +, zip(xs, ys))
830+
831+
# Let's test that `Broadcasted` actually hits the efficient
832+
# `mapreduce` method as intended. We are going to invoke `reduce`
833+
# with this *NON-ASSOCIATIVE* binary operator to see what
834+
# associativity is chosen by the implementation:
835+
paren = (x, y) -> "($x,$y)"
836+
# Next, we construct data `xs` such that `length(xs)` is greater
837+
# than short array cutoff of `_mapreduce`:
838+
alphabets = 'a':'z'
839+
blksize = Base.pairwise_blocksize(identity, paren) ÷ length(alphabets)
840+
xs = repeat(alphabets, 2 * blksize)
841+
@test length(xs) > blksize
842+
# So far we constructed the data `xs` and reducing function
843+
# `paren` such that `reduce` and `foldl` results are different.
844+
# That is to say, this `reduce` does not hit the fall-back `foldl`
845+
# branch:
846+
@test foldl(paren, xs) != reduce(paren, xs)
847+
848+
# Now let's try it with `Broadcasted`:
849+
bcraw = Broadcast.broadcasted(identity, xs)
850+
bc = Broadcast.instantiate(bcraw)
851+
# If `Broadcasted` has `IndexLinear` style, it should hit the
852+
# `reduce` branch:
853+
@test IndexStyle(bc) == IndexLinear()
854+
@test reduce(paren, bc) == reduce(paren, xs)
855+
# If `Broadcasted` does not have `IndexLinear` style, it should
856+
# hit the `foldl` branch:
857+
@test IndexStyle(bcraw) == IndexCartesian()
858+
@test reduce(paren, bcraw) == foldl(paren, xs)
830859
end

0 commit comments

Comments
 (0)