forked from malkia/go-runner
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathslice.got
105 lines (94 loc) · 2.06 KB
/
slice.got
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package slice(type a, type b a)
// Here we have some utility slice routines
// Map1 provides an in-place map, meaning it modifies its input slice.
// If you still want that data, use the Map function.
func Map1(f func(a) a, slice []a) {
for i,v := range slice {
slice[i] = f(v)
}
}
// Map provides an out-of-place map, meaning it does not modify its
// input slice. It therefore has the advantage that you can Map from
// one type of slice to another.
func Map(f func(a) b, slice []a) []b {
out := make([]b, len(slice))
for i,v := range slice {
out[i] = f(v)
}
return out
}
func Fold(f func(b, a) b, x b, slice []a) b {
for _, v := range slice {
x = f(x, v)
}
return x
}
// Filter returns a slice containing only those elements for which the
// predicate function returns true.
func Filter(f func(a) bool, slice []a) []a {
out := make ([]a, 0, len(slice))
i := 0
for _,v := range slice {
if f(v) {
out = out[0:i+1]
out[i] = v
i++
}
}
return out
}
// Append appends an element to a slice, in-place if possible, and
// expanding if needed.
func Append(slice []a, val a) []a {
length := len(slice)
if cap(slice) == length {
// we need to expand
newsl := make([]a, length, 2*(length+1))
for i,v := range slice {
newsl[i] = v
}
slice = newsl
}
slice = slice[0:length+1]
slice[length] = val
return slice
}
func Repeat(val a, n int) []a {
out := make([]a, n)
for i,_ := range out { out[i] = val }
return out
}
// Cat concatenates two slices, expanding if needed.
func Cat(slices ...[]a) []a {
return Cats(slices)
}
// Cats concatenates several slices, expanding if needed.
func Cats(slices [][]a) []a {
lentot := 0
for _,sl := range slices {
lentot += len(sl)
}
out := make([]a, lentot)
i := 0
for _,sl := range slices {
for _,v := range sl {
out[i] = v
i++
}
}
return out
}
func Reverse(slice []a) (out []a) {
ln := len(slice)
out = make([]a, ln)
for i,v:= range slice {
out[ln-1-i] = v
}
return
}
func Any(f func(a) bool, slice []a) bool {
for _,v:= range slice {
if f(v) { return true }
}
return false
}