1
2
3
4
5
6 package slices
7
8
9 func Map[T1, T2 any](s []T1, f func(T1) T2) []T2 {
10 r := make([]T2, len(s))
11 for i, v := range s {
12 r[i] = f(v)
13 }
14 return r
15 }
16
17
18 func Reduce[T1, T2 any](s []T1, initializer T2, f func(T2, T1) T2) T2 {
19 r := initializer
20 for _, v := range s {
21 r = f(r, v)
22 }
23 return r
24 }
25
26
27 func Filter[T any](s []T, f func(T) bool) []T {
28 var r []T
29 for _, v := range s {
30 if f(v) {
31 r = append(r, v)
32 }
33 }
34 return r
35 }
36
37
38
39 func limiter(x int) byte {
40 switch {
41 case x < 0:
42 return 0
43 default:
44 return byte(x)
45 case x > 255:
46 return 255
47 }
48 }
49
50 var input = []int{-4, 68954, 7, 44, 0, -555, 6945}
51 var limited1 = Map[int, byte](input, limiter)
52 var limited2 = Map(input, limiter)
53
54 func reducer(x float64, y int) float64 {
55 return x + float64(y)
56 }
57
58 var reduced1 = Reduce[int, float64](input, 0, reducer)
59 var reduced2 = Reduce(input, 1i , reducer)
60 var reduced3 = Reduce(input, 1, reducer)
61
62 func filter(x int) bool {
63 return x&1 != 0
64 }
65
66 var filtered1 = Filter[int](input, filter)
67 var filtered2 = Filter(input, filter)
68
69
View as plain text