# How to write nested reducibles in Transducers.jl

**URL:** <https://discourse.julialang.org/t/how-to-write-nested-reducibles-in-transducers-jl/84199>\
**Category:** General Usage\
**Tags:** transducers\
**Created:** [July 13, 2022, 9:44pm UTC](https://discourse.julialang.org/t/how-to-write-nested-reducibles-in-transducers-jl/84199 "2022-07-13T21:44:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![nielsls](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nielsls/32/18482_2.png) [@nielsls](https://discourse.julialang.org/u/nielsls)\
**Post date:** [July 13, 2022, 9:44pm UTC](https://discourse.julialang.org/t/how-to-write-nested-reducibles-in-transducers-jl/84199/1 "2022-07-13T21:44:32Z")

</div>

[Writing reducibles · Transducers.jl](https://juliafolds.github.io/Transducers.jl/stable/howto/reducibles/) describes how to make a non-iterable collection reducible; e.g. how to use it as input to transducers. But it does not describe how to delegate the reducing operation to another `reducible`.

MWE is:

`A` and `B` are structs and `A` contains `B`:

```julia
struct B
    arr::Vector{Int}
end

struct A
    b::B
end

a = A(B([1,2,3,3]))

```

Then I try to make `A` and `B` reducible, such that:

- folding over `A` should just fold over the `B` inside `A`, and
- folding over `B` should just fold over the array in `B`.

i.e. `foldl(op, a) == foldl(op, a.b) == foldl(op, a.b.arr)` for some `op`.

```julia
using Transducers

function Transducers. __foldl__ (rf, init, a::A) 
    init = foldl(rf, a.b |> Transducers.IdentityTransducer(); init)
    return Transducers.complete(rf, init)
end

function Transducers. __foldl__ (rf, init, b::B)
    init = foldl(rf, b.arr; init)
    return Transducers.complete(rf, init)
end

```

And then:

```julia
a.b |> Map(string) |> collect # works
a |> Map(string) |> collect # works
a.b |> Map(string) |> Unique() |> collect # works
a |> Map(string) |> Unique() |> collect # FAILS?!

```

It seems that when using `Unique()` it packs some private state that makes the whole thing go down in flames…  
So how should I write my ` __foldl__ ` to avoid this? Without resorting to the iterator-based `@next` pattern…
