-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path043_reduce.go
52 lines (41 loc) · 830 Bytes
/
043_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
50
51
52
package main
import "fmt"
type Numeric interface {
~int | ~float32
}
type Reducible[T Numeric] interface {
Reduce(func(T, T) T) T
}
type ISlice []int
func (s ISlice) Reduce(f func(x, v int) int) (r int) {
for _, v := range s {
r = f(r, v)
}
return
}
type FArray [3]float32
func (a FArray) Reduce(f func(x, v float32) float32) (r float32) {
for _, v := range a {
r = f(r, v)
}
return
}
func Reduce[T Numeric](c any, f func(T, T) T) (r T) {
switch c := c.(type) {
case Reducible[T]:
r = c.Reduce(f)
}
return
}
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 main() {
DoReduce(ISlice{0, 1, 2, 3, 4}, func(x, v int) int {
return x + v
})
DoReduce(FArray{0, 1, 2}, func(x, v float32) float32 {
return x + v
})
}