Add yield types for range over function

145 views
Skip to first unread message

lijh8

unread,
Aug 21, 2024, 4:48:19 PM8/21/24
to golang-nuts
Hi community,

The type of yield occurs twice in the function declaration and 
at the return statement.

```

func (s *Set[E]) All() iter.Seq[E] {
    return func(yield func(E) bool) {
        for v := range s.m {
            if !yield(v) {
                return
            }
        }
    }
}

```

How about add yield types like this?
I think it can simplify the code a bit.

```

type Yield[V any] func(V) bool
type Yield2[K, V any] func(K, V) bool

func sliceDemo[K int, V any](s []V) func(Yield2[K, V]) {
return func(yield Yield2[K, V]) {
for i, v := range s {
if !yield(K(i), v) {
break
}
}
}
}

func mapDemo[K comparable, V any](s map[K]V) func(Yield2[K, V]) {
return func(yield Yield2[K, V]) {
for i, v := range s {
if !yield(i, v) {
break
}
}
}
}

```

Axel Wagner

unread,
Aug 22, 2024, 12:21:18 AM8/22/24
to lijh8, golang-nuts
The plan is, to introduce type-aliases in the `iter` package:
type Yield[E any] = func(E) bool
type Yield2[K, V any] = func(K, V) bool
The reason to make these type-aliases instead of defined types is that it should be possible to define iterators without needing to import the `iter` package. But we still need to be assignable to `iter.Seq`. With defined types, that wouldn't be possible.

However, making them type-aliases, is blocked on #46477. But it should happen for Go 1.124

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/tencent_7983E02A0C5363ABC9B43CD458E0A1B7FC07%40qq.com.

lijh8

unread,
Aug 22, 2024, 5:04:25 AM8/22/24
to Axel Wagner, golang-nuts
Hi,

Do you mean that if the new Yield types are in the iter package, 
it can be used after that?

```

type Yield[V any] func(V) bool
type Yield2[K comparable, V any] func(K, V) bool
type Seq[E any] func(Yield[E])
type Seq2[K comparable, V any] func(Yield2[K, V])

// not importing iter, so can't use the named types
func All2[E any](s []E) func(func(E) bool) {
return func(yield func(E) bool) {
for _, v := range s {
if !yield(v) {
return
}
}
}
}

func All2_b[E any](s []E) Seq[E] {
return func(yield Yield[E]) {
for _, v := range s {
if !yield(v) {
return
}
}
}
}

```

Axel Wagner

unread,
Aug 22, 2024, 6:14:29 AM8/22/24
to lijh8, golang-nuts
I don't really understand the question. What I'm saying is
1. we don't want them to be defined types, because of the issue I described, so
2. it probably needs to be possible to have generic type aliases first and
3. once that is possible, we might add `Yield` and `Yield2` as type-aliases to the `iter` package.
And if that happens, then yes, you could use them, of course.
Reply all
Reply to author
Forward
0 new messages