reduce(op, itr)
reduce(op, itr)
Like reduce(op, v0, itr)
. This cannot be used with empty collections, except for some special cases (e.g. when op
is one of +
, *
, max
, min
, &
, |
) when Julia can determine the neutral element of op
.
Examples
julia> reduce(-, 1:5)
-13
julia> reduce(+, 1:5)
15
-
Calculate the sum of an array:
julia> arr = [1, 2, 3, 4, 5]; julia> reduce(+, 0, arr) 15
This example uses the
reduce
function to calculate the sum of all elements in the arrayarr
. The+
operator is used as the binary operator, and0
is the neutral element for addition. -
Find the maximum value in a collection:
julia> collection = [7, 2, 9, 5, 1]; julia> reduce(maximum, collection) 9
Here, the
reduce
function is used with themaximum
function to find the maximum value in the collection. -
Concatenate strings in a collection:
julia> strings = ["Hello", ", ", "world", "!"]; julia> reduce(*, strings) "Hello, world!"
In this example, the
reduce
function is used with the*
operator to concatenate the strings in the collection. - Handle empty collections with a default value:
julia> empty_collection = Int[]; julia> reduce(+, 0, empty_collection) 0
When reducing an empty collection, the
v0
value (in this case,0
) is returned as the result.
Note: It is recommended to use specialized functions like sum
, prod
, maximum
, etc., when applicable, as they have optimized implementations for specific operations.
See Also
append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.