mapfoldr(f, op, itr)

..  mapfoldr(f, op, itr)

Like ``mapfoldr(f, op, v0, itr)``, but using the first element of
``itr`` as ``v0``. In general, this cannot be used with empty
collections (see ``reduce(op, itr)``).

Examples

  1. Apply a function and a binary operator to an iterable in a right-associative manner:

    julia> add(x, y) = x + y;
    julia> multiply(x, y) = x * y;
    julia> mapfoldr(multiply, add, 1, [2, 3, 4])
    25

    This example applies the multiply function and the add binary operator to the elements of the iterable in a right-associative manner. The initial value v0 is set to 1, and the iterable is [2, 3, 4].

  2. Perform a right-associative reduction on a collection of strings:

    julia> concat(s1, s2) = s1 * s2;
    julia> mapfoldr(concat, string, "", ["Hello", " ", "World"])
    "World Hello"

    Here, the concat function is used to concatenate strings in a right-associative manner. The binary operator string is used to convert the elements of the iterable to strings, and the initial value v0 is an empty string. The iterable is ["Hello", " ", "World"].

  3. Handle an empty iterable:
    julia> mapfoldr(iseven, ||, false, [])
    false

    This example demonstrates how the mapfoldr function handles an empty iterable. The initial value v0 is set to false, and since there are no elements in the iterable, v0 is returned as the result.

Common mistake example:

julia> mapfoldr(sqrt, +, 0, [1, 4, 9])
ERROR: MethodError: no method matching sqrt(::Int64)

In this example, the sqrt function is applied to the elements of the iterable, but it can only operate on floating-point numbers. It's important to ensure that the function passed to mapfoldr is compatible with the elements in the iterable to avoid such errors.

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.

*Required Field
Details

Checking you are not a robot: