iter.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "fmt"
  4. "iter"
  5. )
  6. var max = 5
  7. func s0(yield func() bool) {
  8. for i := 0; i < max; i++ {
  9. res := yield()
  10. fmt.Printf("s0 yield(%d) %t\n", i, res)
  11. }
  12. }
  13. func s1(yield func(y int) bool) {
  14. var res = true
  15. // Stop on our terms, OR if a break was used in the for loop.
  16. for i := 0; i < max && res; i++ {
  17. res = yield(i)
  18. fmt.Printf("s1 yield(%d) %t\n", i, res)
  19. }
  20. }
  21. func s2(yield func(k int, v int) bool) {
  22. for x, sq := 0, 0; sq < max; x++ {
  23. sq = x * x
  24. res := yield(x, sq)
  25. fmt.Printf("yield(%d, %d) %t\n", x, sq, res)
  26. }
  27. }
  28. func main() {
  29. //for range s0 {
  30. // fmt.Print("In range s0: ")
  31. //}
  32. //fmt.Println()
  33. //
  34. //for k := range s1 {
  35. // fmt.Print("In range s1 ")
  36. // if k > max/2 {
  37. // break
  38. // }
  39. //}
  40. //fmt.Println()
  41. //
  42. //for k := range s2 {
  43. // fmt.Print("In range s2 ")
  44. // if k > max/2 {
  45. // break
  46. // }
  47. //}
  48. //fmt.Println()
  49. //
  50. //for k, v := range s2 {
  51. // fmt.Printf("In range s2 %d/%d ", k, v)
  52. // if k > max/2 {
  53. // break
  54. // }
  55. //}
  56. next, stop := iter.Pull(s1)
  57. nw := func() (int, bool) {
  58. k, ok := next()
  59. fmt.Printf("next(%d) %t\n", k, ok)
  60. return k, ok
  61. }
  62. for k, ok := nw(); ok; k, ok = next() {
  63. fmt.Printf("k: %d, ok: %t\n", k, ok)
  64. if k > max/2 {
  65. stop()
  66. }
  67. }
  68. }