]> Cypherpunks repositories - gostls13.git/commitdiff
spec: better examples for range-over-func
authorRobert Griesemer <gri@golang.org>
Tue, 4 Jun 2024 17:59:00 +0000 (10:59 -0700)
committerGopher Robot <gobot@golang.org>
Tue, 4 Jun 2024 21:07:21 +0000 (21:07 +0000)
For #65237.

Change-Id: Id38747efebd46633f453eadaf68d818064faa778
Reviewed-on: https://go-review.googlesource.com/c/go/+/590396
Reviewed-by: Robert Griesemer <gri@google.com>
TryBot-Bypass: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>

doc/go_spec.html

index 748fcc1ba02cbd740f2e0f2ef6142897af991972..d1ca6722e104a9021f0bdaa46282f9925b37eb2b 100644 (file)
@@ -6804,15 +6804,43 @@ for u = range 256 {
 // invalid: 1e3 is a floating-point constant
 for range 1e3 {
 }
-<!-- TODO(gri) need better examples for range-over-func -->
-// print hello world
-f := func(yield func(string) bool) {
-       if yield("hello") {
-               yield("world")
+
+// fibo generates the Fibonacci sequence
+fibo := func(yield func(x int) bool) {
+       f0, f1 := 0, 1
+       for yield(f0) {
+               f0, f1 = f1, f0+f1
+       }
+}
+
+// print the Fibonacci numbers below 1000:
+for x := range fibo {
+       if x >= 1000 {
+               break
        }
+       fmt.Printf("%d ", x)
+}
+// output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
+
+// iteration support for a recursive tree data structure
+type Tree[K cmp.Ordered, V any] struct {
+       left, right *Tree[K, V]
+       key         K
+       value       V
 }
-for word := range f {
-       println(word)
+
+func (t *Tree[K, V]) walk(yield func(key K, val V) bool) bool {
+       return t == nil || t.left.walk(yield) && yield(t.key, t.value) && t.right.walk(yield)
+}
+
+func (t *Tree[K, V]) Walk(yield func(key K, val V) bool) {
+       t.walk(yield)
+}
+
+// walk tree t in-order
+var t Tree[string, int]
+for k, v := range t.Walk {
+       // process k, v
 }
 </pre>