Skip to content

Commit

Permalink
Rename range over iterators sample and add a bit more sample
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Aug 21, 2024
1 parent 4d27fb5 commit a0e4c07
Show file tree
Hide file tree
Showing 9 changed files with 117 additions and 19 deletions.
2 changes: 1 addition & 1 deletion examples.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Interfaces
Enums
Struct Embedding
Generics
Range over Custom Types
Range over Iterators
Errors
Custom Errors
Goroutines
Expand Down
2 changes: 0 additions & 2 deletions examples/range-over-custom-types/range-over-custom-types.hash

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Starting with version 1.23, Go has added support for
// [iterators](https://go.dev/blog/range-functions),
// which lets us range over custom types.
// which lets us range over pretty much anything!

package main

Expand Down Expand Up @@ -51,6 +51,23 @@ func (lst *List[T]) All() iter.Seq[T] {
}
}

// Iteration doesn't require an underlying data structure,
// and doesn't even have to be finite! Here's a function
// returning an iterator over Fibonacci numbers: it keeps
// running as long as `yield` keeps returning `true`.
func genFib() iter.Seq[int] {
return func(yield func(int) bool) {
a, b := 1, 1

for {
if !yield(a) {
return
}
a, b = b, a+b
}
}
}

func main() {
lst := List[int]{}
lst.Push(10)
Expand All @@ -69,4 +86,14 @@ func main() {
// all its values into a slice.
all := slices.Collect(lst.All())
fmt.Println("all:", all)

for n := range genFib() {

// Once the loop hits `break` or an early return, the `yield` function
// passed to the iterator will return `false`.
if n >= 10 {
break
}
fmt.Println(n)
}
}
2 changes: 2 additions & 0 deletions examples/range-over-iterators/range-over-iterators.hash
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
375f830fbe82633900d572c9077302143463a2e3
BayyagaCK83
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,10 @@
13
23
all: [10 13 23]
1
1
2
3
5
8

2 changes: 1 addition & 1 deletion public/errors

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions public/generics

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion public/index.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

87 changes: 76 additions & 11 deletions public/range-over-custom-types → public/range-over-iterators

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a0e4c07

Please sign in to comment.