foldr(op, itr)
.. foldr(op, itr)
Like ``foldr(op, v0, itr)``, but using the last element of ``itr``
as ``v0``. In general, this cannot be used with empty collections
(see ``reduce(op, itr)``).
Examples
In the Julia programming language, the function foldr(op, v0, itr)
is similar to the reduce
function, but with guaranteed right associativity. It takes an operator op
, an initial value v0
, and an iterable itr
as arguments. The operator is applied to each element of the iterable from right to left, using the initial value as the starting point.
julia> foldr(+, 0, [1, 2, 3, 4])
10
julia> foldr(string, "", ["Hello", " ", "World", "!"])
"!World Hello"
-
Summing elements in an array:
julia> arr = [1, 2, 3, 4, 5]; julia> foldr(+, 0, arr) 15
This example calculates the sum of all elements in the array
arr
using the+
operator and an initial value of0
. -
Concatenating strings:
julia> strings = ["Hello", " ", "Julia"]; julia> foldr(string, "", strings) "Julia Hello "
It concatenates the strings in the
strings
array from right to left, using an initial value of an empty string. - Applying a custom function:
julia> double(x, y) = 2x + y; julia> foldr(double, 0, [1, 2, 3, 4]) 26
In this example, the custom function
double
is applied to each element of the array, accumulating the result from right to left.
Common mistake example:
julia> foldr(-, 0, [1, 2, 3, 4])
ERROR: MethodError: no method matching foldr(::typeof(-), ::Int64, ::Array{Int64,1})
In this case, the -
operator cannot be directly used with foldr
because it requires two arguments. To fix this, you can define a custom function or use an anonymous function to perform the subtraction:
julia> foldr((x, y) -> x - y, 0, [1, 2, 3, 4])
-2
Ensure that the operator or function you provide to foldr
can handle the right-to-left accumulation correctly.
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.