mapreduce(f, op, itr)
.. mapreduce(f, op, itr)
Like ``mapreduce(f, op, v0, itr)``. In general, this cannot be used
with empty collections (see ``reduce(op, itr)``).
Examples
The mapreduce(f, op, v0, itr)
function is used to apply a function f
to each element in an iterable itr
, and then reduce the result using the binary function op
. The initial value v0
is a neutral element for op
and will be returned for empty collections.
julia> mapreduce(x -> x^2, +, 1:3)
14
In this example, the function f
squares each element in the range 1:3
, and then the +
operator is used to sum up the squared values, resulting in 14
.
The mapreduce
function is functionally equivalent to calling reduce(op, v0, map(f, itr))
, but it generally executes faster since no intermediate collection needs to be created.
Note that the associativity of the reduction is implementation-dependent, and some implementations may reuse the return value of f
for elements that appear multiple times in itr
. If you need guaranteed left or right associativity and invocation of f
for every value, consider using mapfoldl
or mapfoldr
instead.
julia> mapfoldl(x -> x^2, +, 0, 1:3)
14
In this example, mapfoldl
is used to ensure left associativity and invocation of f
for every value in the range 1:3
. The result is the same as with mapreduce
.
It's important to note that the behavior of v0
for non-empty collections is unspecified. Therefore, it's recommended to use v0
only for empty collections and not rely on its usage for non-empty collections.
See Also
foldl, foldr, mapfoldl, mapfoldr, mapreduce, mapreducedim,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.