Skip to content

Document op argument order in foldl #53562

Open
@jariji

Description

@jariji

foldl(op, itr; [init])

Like reduce, but with guaranteed left associativity. If provided, the keyword argument init will be used exactly
once. In general, it will be necessary to provide init to work with empty collections.

See also mapfoldl, foldr, accumulate.

Examples
≡≡≡≡≡≡≡≡

julia> foldl(=>, 1:4)
((1 => 2) => 3) => 4

julia> foldl(=>, 1:4; init=0)
(((0 => 1) => 2) => 3) => 4

julia> accumulate(=>, (1,2,3,4))
(1, 1 => 2, (1 => 2) => 3, ((1 => 2) => 3) => 4)

I don't think it's clear from this whether op will always receive (accumulator, x) or (x, accumulator). The answer is (accumulator, x) which is necessary in order to support asymmetric ops like push!:

julia> foldl(push!, 1:2; init=Int[])
2-element Vector{Int64}:
 1
 2

We might guess that's what it means from the examples, but you can't really infer it's a guarantee rather than a current implementation detail.

Metadata

Metadata

Assignees

No one assigned

    Labels

    foldsum, maximum, reduce, foldl, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions