Skip to content

Instantly share code, notes, and snippets.

@LeoCBS
Created December 14, 2024 13:09
Show Gist options
  • Save LeoCBS/0ebe7cc5ffcc29ccb7004a76dd924234 to your computer and use it in GitHub Desktop.
Save LeoCBS/0ebe7cc5ffcc29ccb7004a76dd924234 to your computer and use it in GitHub Desktop.
Golang iterator example 1.23
package main
import "fmt"
// Seq is an iterator over sequences of individual values.
// When called as seq(yield), seq calls yield(v) for each value v
// in the sequence, stopping early if yield returns false.
// type Seq[V any] func(yield func(V) bool)
// our iterator function takes in a value and returns a func
// that takes in another func with a signature of `func(int) bool`
func Countdown(v int) func(func(int) bool) {
// next, we return a callback func which is typically
// called yield, but names like next could also be
// applicable
return func(yield func(int) bool) {
// we then start a for loop that iterates
for i := v; i >= 0; i-- {
// once we've finished looping
if !yield(i) {
// we then return and finish our iterations
return
}
}
}
}
func main() {
for x := range Countdown(10) {
fmt.Println(x)
}
}
@LeoCBS
Copy link
Author

LeoCBS commented Dec 14, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment