-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path046_reduce.go
48 lines (41 loc) · 870 Bytes
/
046_reduce.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
package main
import "fmt"
type Numeric interface {
~int | ~float32
}
func Reduce[T Numeric](c any, f func(T, T) T) (r T) {
switch c := c.(type) {
case func(int) (T, bool):
for i := 0; ; i++ {
if v, ok := c(i); ok {
r = f(r, v)
} else {
break
}
}
case NFunc[T]:
r = Reduce((func(int) (T, bool))(c), f)
}
return
}
type NFunc[T Numeric] func(int) (T, bool)
func DoReduce[T Numeric](c any, f func(T, T) T) {
r := Reduce(c, f)
fmt.Printf("[%T]Reduce(%v, f()) = %v[%T]\n", c, c, r, r)
}
func Adder[T Numeric]() func(T, T) T {
return func(x, v T) T {
return x + v
}
}
func main() {
DoReduce(func(x int) (int, bool) {
return x, (x < 5)
}, Adder[int]())
DoReduce(func(x int) (float32, bool) {
return float32(x), (x < 5)
}, Adder[float32]())
DoReduce(NFunc[int](func(x int) (int, bool) {
return x, (x < 5)
}), Adder[int]())
}