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)``).Examples
-
Sum all elements in an array:
julia> arr = [1, 2, 3, 4, 5]; julia> foldl(+, 0, arr) 15This example uses the
foldlfunction to sum all elements in the arrayarr. -
Concatenate strings in an array:
julia> words = ["Hello", ", ", "Julia!"]; julia> foldl(*, "", words) "Hello, Julia!"It concatenates the strings in the
wordsarray usingfoldlwith the multiplication operator*. - Find the minimum value in an array:
julia> nums = [10, 5, 8, 3, 12]; julia> foldl(min, Inf, nums) 3Using
foldlwith theminfunction andInfas the initial value, it finds the minimum value in thenumsarray.
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.