On 23/05/24, Rory Campbell-Lange (
ro...@campbell-lange.net) wrote:
> I've been playing with with rangefunc experiment...
...reference to python nested yield example...
> for p in people:
> for c in p.cars:
> for t in c.tickets:
> print("person {} in car {} got ticket {}", p, c, t)
>
> [My attempt to recreate in go at]
https://go.dev/play/p/gFUcKNSrbMV?v=gotip ... only has an iterator on the left hand side and series of nested structs through slices...
For info, in my attempt to use nested iter.Seq structures I (obviously) didn't need a restart, but simply yielded the left-most struct and used the iterators in each nested struct as required. I've got this sort of working as shown below -- sorry if my plain text email formatting gets lost in translation.
type obj[T comparable, U any] struct {
this T
those []U
}
func (o *obj[T, U]) Add(u U) {
o.those = append(o.those, u)
}
func (o *obj[T, U]) Eq(n T) bool {
return o.this == n
}
// Iter could take args for customization
func (o *obj[T, U]) Iter() iter.Seq[U] {
if debug {
fmt.Printf("calling Iter() on %T\n", o.those)
}
return func(yield func(U) bool) {
for _, v := range o.those {
if !yield(v) {
return
}
}
}
}
It's painful to work with so probably not worth the effort. See:
https://go.dev/play/p/PpKpAIz7u6J?v=gotip
Example output from
a1 a1a a1b 1.1 1.2 1.3 n1 n1a n1b
a1 a1a a1b 1.1 1.2 1.3 n2 n2a n2b
a1 a1a a1b 1.1 1.2 1.3 n3 n3a n3b
a1 a1a a1b 2.1 2.2 2.3 n4 n4a n4b
a2 a2a a2b 3.1 3.2 3.3 n5 n5a n6b
a2 a2a a2b 3.1 3.2 3.3 n6 n5a n6b
is as follows:
{a1 a1a a1b}
calling Iter() on []main.obj[main.b,main.c]
> {1.1 1.2 1.3}
calling Iter() on []main.c
> > {n1 n1a n1b}
> {1.1 1.2 1.3}
calling Iter() on []main.c
> > {n1 n1a n1b}
> > {n2 n2a n2b}
> {1.1 1.2 1.3}
calling Iter() on []main.c
> > {n1 n1a n1b}
> > {n2 n2a n2b}
> > {n3 n3a n3b}
> {2.1 2.2 2.3}
calling Iter() on []main.c
> > {n4 n4a n4b}
{a2 a2a a2b}
calling Iter() on []main.obj[main.b,main.c]
> {3.1 3.2 3.3}
calling Iter() on []main.c
> > {n5 n5a n6b}
> {3.1 3.2 3.3}
calling Iter() on []main.c
> > {n5 n5a n6b}
> > {n6 n5a n6b}