Skip to content

proposal: x/exp/xiter: Add transformers between iter.Seq and iter.Seq2 #69702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
eikemeier opened this issue Sep 28, 2024 · 2 comments
Closed
Labels
Milestone

Comments

@eikemeier
Copy link

Proposal Details

Sometimes one has a iter.Seq and needs a iter.Seq2 or vice versa. On example could be slices.Backward, which results in a iter.Seq2 and slices.Collect which takes an iter.Seq

Proposed are two mapping functions:

// Map21 returns an iterator over f applied to seq.
func Map21[KIn, VIn, Out any](f func(KIn, VIn) Out, seq iter.Seq2[KIn, VIn]) iter.Seq[Out]

// Map12 returns an iterator over f applied to seq.
func Map12[In, KOut, VOut any](f func(In) (KOut, VOut), seq iter.Seq[In]) iter.Seq2[KOut, VOut]

and two convenience functions:

// Values returns an iterator over seq  with the first elements dropped.
func Values[KIn, VIn any](seq iter.Seq2[KIn, VIn]) iter.Seq[VIn]

// Sequence2 returns a counted iterator over seq.
func Sequence2[In any](seq iter.Seq[In]) iter.Seq2[int, In]

With the following implementation ( Go playground):

// Map21 returns an iterator over f applied to seq.
func Map21[KIn, VIn, Out any](f func(KIn, VIn) Out, seq iter.Seq2[KIn, VIn]) iter.Seq[Out] {
	return func(yield func(Out) bool) {
		for k, v := range seq {
			if !yield(f(k, v)) {
				return
			}
		}
	}
}

// Map12 returns an iterator over f applied to seq.
func Map12[In, KOut, VOut any](f func(In) (KOut, VOut), seq iter.Seq[In]) iter.Seq2[KOut, VOut] {
	return func(yield func(KOut, VOut) bool) {
		for in := range seq {
			if !yield(f(in)) {
				return
			}
		}
	}
}

// Values returns an iterator over seq  with the first elements dropped.
func Values[KIn, VIn any](seq iter.Seq2[KIn, VIn]) iter.Seq[VIn] {
	return Map21(func(_ KIn, v VIn) VIn { return v }, seq)
}

// Sequence2 returns a counted iterator over seq.
func Sequence2[In any](seq iter.Seq[In]) iter.Seq2[int, In] {
	return func(yield func(int, In) bool) {
		k := 0
		for in := range seq {
			if !yield(k, in) {
				return
			}
			k++
		}
	}
}
@gopherbot gopherbot added this to the Proposal milestone Sep 28, 2024
@gabyhelp
Copy link

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@eikemeier
Copy link
Author

eikemeier commented Sep 28, 2024

Related Issues and Documentation

Thanks @gabyhelp. Also, I realized that @bcmills already suggested this.

Also, already discussed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants