/
ops.go
64 lines (59 loc) · 1.81 KB
/
ops.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
53
54
55
56
57
58
59
60
61
62
63
64
package list
import "errors"
// Cons creates a new list with head at the front of tail
func Cons[T any](head T, tail []T) []T {
lst := []T{head}
return append(lst, tail...)
}
// Head returns slc[0] if the list has at least one element
// in it. Otherwise, returns empty() and a descriptive,
// non-nil error
func Head[T any](slc []T, empty func() T) (T, error) {
if len(slc) == 0 {
return empty(), errors.New("Head called on empty list")
}
return slc[0], nil
}
// Tail returns all but the first element of slc.
// If slc has less than 2 elements in it, returns nil
// and a non-nil, descriptive error.
func Tail[T any](slc []T) ([]T, error) {
if len(slc) < 2 {
return nil, errors.New("Tail called on empty list")
}
return slc[1:], nil
}
// Zip combines slc1 and slc2 together.
// Starting at index 0, every odd number index in the
// returned slice will be the next successive element in
// slc1, and even number will be the next in slc2.
//
// If either slice is longer than the other, the remainder
// of the returned slice will have the rest of the
// elements in the longer slice
func Zip[T any](slc1 []T, slc2 []T) []T {
totalRet := len(slc1) + len(slc2)
ret := make([]T, len(slc1)+len(slc2))
slc1Idx := 0
slc2Idx := 0
for i := 0; i < totalRet; i++ {
if i%2 == 0 && slc1Idx < len(slc1) {
// even number, take from slice 1 if possible
ret[i] = slc1[slc1Idx]
slc1Idx++
} else if i%2 != 0 && slc2Idx < len(slc2) {
// odd number, take from slice 2 if possible
ret[i] = slc2[slc2Idx]
slc2Idx++
} else if slc1Idx < len(slc1) {
// not even number but we're past the end of slice 2, take from slice 1
ret[i] = slc1[slc1Idx]
slc1Idx++
} else if slc2Idx < len(slc2) {
// not odd number but we're past the end of slice 1, take from slice 2
ret[i] = slc2[slc2Idx]
slc2Idx++
}
}
return ret
}