1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package slices implements various slice algorithms.
6 package slices
7
8 // Map turns a []T1 to a []T2 using a mapping function.
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 // Reduce reduces a []T1 to a single value using a reduction function.
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 // Filter filters values from a slice using a filter function.
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 // Example uses
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) // using type inference
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 /* ERROR overflows */, reducer) // using type inference
60 var reduced3 = Reduce(input, 1, reducer) // using type inference
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) // using type inference
68
69
View as plain text