SIGN IN SIGN UP

Fix interaction between `foldr` and `Iterators.flatten` (#61806)

Fixes https://github.com/JuliaLang/julia/issues/61805

It seems that the problem is that our `foldr_impl` is passing a
non-reversed iterator to `_xfadjoint`, and then doing the actual final
reduction on a reversed iterator. This is normally fine, but it
interacts incorrectly with `FlatteningRF` which does a sub-reduction
inside each reducing step:
```julia
@inline function (op::FlatteningRF)(acc, x)
    op′, itr′ = _xfadjoint(op.rf, x)
    return _foldl_impl(op′, acc, itr′)
end
```
and this sub-reduction is not reversed when it gets hit during `foldr`,
resulting in the weird reduction order shown in the linked issue:
```julia
julia> foldr(Iterators.flatten([["a","b"],["c","d"]])) do l, r
           @info "" l r
           l * r
       end
┌ Info: 
│   l = "d"
└   r = "c"
┌ Info: 
│   l = "a"
└   r = "dc"
┌ Info: 
│   l = "b"
└   r = "adc"
"badc"
```

This PR changes around the location of the `_reverse_iter` so that the
sub-reductions are also reversed:

```julia

julia> foldr(Iterators.flatten([["a","b"],["c","d"]])) do l, r
           @info "" l r
           l * r
       end
┌ Info: 
│   l = "c"
└   r = "d"
┌ Info: 
│   l = "b"
└   r = "cd"
┌ Info: 
│   l = "a"
└   r = "bcd"
"abcd"
```

---------

Co-authored-by: Andy Dienes <51664769+adienes@users.noreply.github.com>
Co-authored-by: Matt Bauman <mbauman@juliahub.com>
M
Mason Protter committed
ccd0279103652707a90b85ef783c52a1304613f4
Parent: 3028843
Committed by GitHub <noreply@github.com> on 5/15/2026, 11:55:32 AM