-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiter.go
77 lines (64 loc) · 2.26 KB
/
iter.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
71
72
73
74
75
76
77
// This package wraps the standard library's [iter] package, providing some
// additional features.
//
// It is intended to potentially inform future development and act as the
// backbone of this library.
package fp
import (
"iter"
)
// SeqFunc is exactly the same as [iter.Seq] and can be trivially cast between
type SeqFunc[V any] iter.Seq[V]
// Seq borrows a trick used by [http.Handler] to define an interface and a func
// that implements that interface by calling itself [SeqFunc]
type Seq[V any] interface {
// Seq implements push-style iteration using the yield callback.
// See the documenation of [iter] for more information.
// It has exactly the same signature as [SeqFunc].
// This function can be used directly with the for-range statement
Seq(yield func(V) bool)
}
func (sf SeqFunc[V]) Seq(yield func(V) bool) {
sf(yield)
}
// KeyValue is a key-value pair
type KeyValue[K comparable, V any] struct {
Key K
Value V
}
// Seq2Func is exactly the same as [iter.Seq2] and can be trivially cast between.
type Seq2Func[K comparable, V any] iter.Seq2[K, V]
// Seq2 is to [Seq] what [iter.Seq] is to [iter.Seq2]
// but with the additional requirement that Seq2 implements [Seq]
type Seq2[K comparable, V any] interface {
// I don't like the whole [iter.Seq2] thing that the stdlib does
// so we use this to convert [Seq2] into [Seq]
// This trivially gives compatibility with the rest of this library
Seq(yield func(KeyValue[K, V]) bool)
Seq2(yield func(K, V) bool)
}
func (sf Seq2Func[K, V]) Seq(yield func(KeyValue[K, V]) bool) {
sf(func(k K, v V) bool {
return yield(KeyValue[K, V]{k, v})
})
}
func (sf Seq2Func[K, V]) Seq2(yield func(K, V) bool) {
sf(yield)
}
// Pull is a wrappr around [iter.Pull]
func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func()) {
return iter.Pull(seq.Seq)
}
// Pull2 is a wrapper around [iter.Pull2]
func Pull2[K comparable, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func()) {
return iter.Pull2(seq.Seq2)
}
// Duet is the inverse of [Seq2.Seq] taking a [Seq] of [KeyValue]
// and returning the [Seq2] equivalent
func Duet[K comparable, V any](seq Seq[KeyValue[K, V]]) Seq2[K, V] {
return Seq2Func[K, V](func(yield func(K, V) bool) {
seq.Seq(func(kv KeyValue[K, V]) bool {
return yield(kv.Key, kv.Value)
})
})
}