Skip to content

Commit 17a1e2f

Browse files
committed
Add divide-and-conquer _mapreduce
1 parent 621d50a commit 17a1e2f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/mapreduce.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,28 @@ end
112112

113113
@inline _mapreduce(args::Vararg{Any,N}) where N = _mapfoldl(args...)
114114

115+
@generated function _mapreduce(f, op, dims::Colon, init, ::Size{S}, a::StaticArray...) where {S}
116+
function op_expr(idx)
117+
if length(idx) == 1
118+
i, = idx
119+
tmp = [:(a[$j][$i]) for j 1:length(a)]
120+
expr = :(f($(tmp...)))
121+
if init === _InitialValue
122+
return :(Base.reduce_first(op, $expr))
123+
else
124+
return :(op(init, $expr))
125+
end
126+
end
127+
left = op_expr(idx[1:end÷2])
128+
right = op_expr(idx[end÷2+1:end])
129+
return :(op($left, $right))
130+
end
131+
return quote
132+
@_inline_meta
133+
@inbounds return $(op_expr(1:prod(S)))
134+
end
135+
end
136+
115137
@generated function _mapfoldl(f, op, dims::Colon, init, ::Size{S}, a::StaticArray...) where {S}
116138
tmp = [:(a[$j][1]) for j 1:length(a)]
117139
expr = :(f($(tmp...)))

0 commit comments

Comments
 (0)