From: Robert Griesemer Date: Tue, 4 Jun 2024 17:59:00 +0000 (-0700) Subject: spec: better examples for range-over-func X-Git-Tag: go1.23rc1~85 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=1724c261422bcaac33126e7408c26e024870ba07;p=gostls13.git spec: better examples for range-over-func For #65237. Change-Id: Id38747efebd46633f453eadaf68d818064faa778 Reviewed-on: https://go-review.googlesource.com/c/go/+/590396 Reviewed-by: Robert Griesemer TryBot-Bypass: Robert Griesemer Reviewed-by: Ian Lance Taylor Auto-Submit: Robert Griesemer --- diff --git a/doc/go_spec.html b/doc/go_spec.html index 748fcc1ba0..d1ca6722e1 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -6804,15 +6804,43 @@ for u = range 256 { // invalid: 1e3 is a floating-point constant for range 1e3 { } - -// 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 }