-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path047_reduce.go
49 lines (42 loc) · 896 Bytes
/
047_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
49
package main
import (
"fmt"
R "reflect"
)
type Numeric interface {
~int | ~float32
}
func Reduce[T Numeric](c any, f func(T, T) T) (r T) {
if c := R.ValueOf(c); c.Kind() == R.Func {
for i := 0; ; i++ {
p := []R.Value{R.ValueOf(i)}
if p = c.Call(p); p[1].Interface() == true {
r = f(r, p[0].Interface().(T))
} else {
break
}
}
}
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]())
}