-
Notifications
You must be signed in to change notification settings - Fork 0
/
25-range-over-iterators.go
71 lines (59 loc) · 1001 Bytes
/
25-range-over-iterators.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"fmt"
"iter"
"slices"
)
type List[T any] struct {
head, tail *element[T]
}
type element[T any] struct {
next *element[T]
val T
}
func (lst *List[T]) Push(v T){
if lst.tail == nil {
lst.head = &element[T]{val: v}
lst.tail = lst.head
}else {
lst.tail.next = &element[T]{val:v}
lst.tail = lst.tail.next
}
}
func (lst *List[T]) All() iter.Seq[T]{
return func(yield func(T) bool){
for e := lst.head; e != nil; e = e.next {
if !yield(e.val){
return
}
}
}
}
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)
lst.Push(13)
lst.Push(23)
for e := range lst.All(){
fmt.Println(e)
}
all := slices.Collect(lst.All())
fmt.Println("all:",all)
for n := range genFib() {
if n >= 10 {
break
}
fmt.Println(n)
}
}