I'm able to capture the input generic sequence type in order to return it like so:
type Seq[V any] interface {
~func(yield func(V) bool)
}
func Filter[V any, SV Seq[V]](s SV, filterFn func(V) bool) SV {
return func(yield func(V) bool) {
for item := range s {
if filterFn(item) {
if !yield(item) {
return
}
}
}
}
}
However, I can't find a way to do this when when the underlying item type changes as per the below example:
func Map[V, U any, SV Seq[V]](s SV, mapFn func(V) U) func(yield func(U) bool) {
// Returning the underlying type as it is a cheap implicit conversion
return func(yield func(U) bool) {
for item := range s {
if !yield(mapFn(item)) {
return
}
}
}
}
Is it possible to capture the input sequence type in order to return it over a new item type? Or is this implementation my next best option?
I'm able to capture the input generic sequence type in order to return it like so:
type Seq[V any] interface {
~func(yield func(V) bool)
}
func Filter[V any, SV Seq[V]](s SV, filterFn func(V) bool) SV {
return func(yield func(V) bool) {
for item := range s {
if filterFn(item) {
if !yield(item) {
return
}
}
}
}
}
However, I can't find a way to do this when when the underlying item type changes as per the below example:
func Map[V, U any, SV Seq[V]](s SV, mapFn func(V) U) func(yield func(U) bool) {
// Returning the underlying type as it is a cheap implicit conversion
return func(yield func(U) bool) {
for item := range s {
if !yield(mapFn(item)) {
return
}
}
}
}
Is it possible to capture the input sequence type in order to return it over a new item type? Or is this implementation my next best option?
Share Improve this question edited Feb 4 at 8:50 blackgreen♦ 45.2k28 gold badges160 silver badges155 bronze badges asked Feb 4 at 7:10 richardpjrichardpj 4314 silver badges11 bronze badges 01 Answer
Reset to default 4You don't need to declare a generic interface for iterators. iter.Seq[V]
is already generic.
Therefore, you simply rewrite your functions as follows:
func Filter[V any](s iter.Seq[V], filterFn func(V) bool) iter.Seq[V] {
return func(yield func(V) bool) {
for item := range s {
if filterFn(item) {
if !yield(item) {
return
}
}
}
}
}
And
func Map[V, U any](s iter.Seq[V], mapFn func(V) U) iter.Seq[U] {
return func(yield func(U) bool) {
for item := range s {
if !yield(mapFn(item)) {
return
}
}
}
}
Playground: https://go.dev/play/p/blX4HgqOwWl