Last active
June 19, 2024 02:00
-
-
Save thwarted/a6e5e7ca5ce552311a7d5ece13d298ac to your computer and use it in GitHub Desktop.
Revisions
-
thwarted revised this gist
Jun 19, 2024 . 1 changed file with 4 additions and 4 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -15,11 +15,11 @@ import ( // upto returns an iterator that emits integers up to the given max func upto(max int) chan int { c := make(chan int) yield := func(i int) { c <- i } go func() { for i := range max { yield(i) } close(c) }() @@ -28,12 +28,12 @@ func upto(max int) chan int { // powersOf2 returns an iterator that emits the powers of 2 up to max func powersOf2(max uint) chan uint { c := make(chan uint) yield := func(i uint) { c <- i } go func() { var cur uint = 1 for cur < max { yield(cur) cur *= 2 } close(c) -
thwarted created this gist
Jun 19, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ package main // A simple go iterator implementation. // Someone could use generics to make this more, well, generic. And // maybe define a Next() function on a channel receiver to abstract // away needing the channel <- operator to get the next item and // and handle the iterator ending cleanly. This uses range which // already knows how to handle streaming values from channels. // // github user: thwarted import ( "fmt" ) // upto returns an iterator that emits integers up to the given max func upto(max int) chan int { yield := func(x chan int, i int) { x <- i } c := make(chan int) go func() { for i := range max { yield(c, i) } close(c) }() return c } // powersOf2 returns an iterator that emits the powers of 2 up to max func powersOf2(max uint) chan uint { yield := func(x chan uint, i uint) { x <- i } c := make(chan uint) go func() { var cur uint = 1 for cur < max { yield(c, cur) cur *= 2 } close(c) }() return c } func main() { myiterator := upto(10) for i := range myiterator { fmt.Println("upto emitted ", i) } fmt.Println() for i := range powersOf2(3000) { fmt.Println("powersOf2 emitted ", i) } }