foldl(op, itr)

..  foldl(op, itr)

Like ``foldl(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)``).


  1. Sum all elements in an array:

    julia> arr = [1, 2, 3, 4, 5];
    julia> foldl(+, 0, arr)

    This example uses the foldl function to sum all elements in the array arr.

  2. Concatenate strings in an array:

    julia> words = ["Hello", ", ", "Julia!"];
    julia> foldl(*, "", words)
    "Hello, Julia!"

    It concatenates the strings in the words array using foldl with the multiplication operator *.

  3. Find the minimum value in an array:
    julia> nums = [10, 5, 8, 3, 12];
    julia> foldl(min, Inf, nums)

    Using foldl with the min function and Inf as the initial value, it finds the minimum value in the nums array.

Common mistake example:

julia> arr = [1, 2, 3, 4, 5];
julia> foldl(-, arr)
ERROR: MethodError: no method matching foldl(::typeof(-), ::Array{Int64,1})

In this example, the foldl function is called without specifying the initial value. It is important to provide the initial value as the second argument to foldl 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

Checking you are not a robot: