1
2
3
4
5 package a
6
7
8
9 func SliceEqual[Elem comparable](s1, s2 []Elem) bool {
10 if len(s1) != len(s2) {
11 return false
12 }
13 for i, v1 := range s1 {
14 v2 := s2[i]
15 if v1 != v2 {
16 isNaN := func(f Elem) bool { return f != f }
17 if !isNaN(v1) || !isNaN(v2) {
18 return false
19 }
20 }
21 }
22 return true
23 }
24
25
26 type Set[Elem comparable] struct {
27 m map[Elem]struct{}
28 }
29
30
31 func Make[Elem comparable]() Set[Elem] {
32 return Set[Elem]{m: make(map[Elem]struct{})}
33 }
34
35
36 func (s Set[Elem]) Add(v Elem) {
37 s.m[v] = struct{}{}
38 }
39
40
41
42 func (s Set[Elem]) Delete(v Elem) {
43 delete(s.m, v)
44 }
45
46
47 func (s Set[Elem]) Contains(v Elem) bool {
48 _, ok := s.m[v]
49 return ok
50 }
51
52
53 func (s Set[Elem]) Len() int {
54 return len(s.m)
55 }
56
57
58
59 func (s Set[Elem]) Values() []Elem {
60 r := make([]Elem, 0, len(s.m))
61 for v := range s.m {
62 r = append(r, v)
63 }
64 return r
65 }
66
67
68 func Equal[Elem comparable](s1, s2 Set[Elem]) bool {
69 if len(s1.m) != len(s2.m) {
70 return false
71 }
72 for v1 := range s1.m {
73 if !s2.Contains(v1) {
74 return false
75 }
76 }
77 return true
78 }
79
80
81 func (s Set[Elem]) Copy() Set[Elem] {
82 r := Set[Elem]{m: make(map[Elem]struct{}, len(s.m))}
83 for v := range s.m {
84 r.m[v] = struct{}{}
85 }
86 return r
87 }
88
89
90 func (s Set[Elem]) AddSet(s2 Set[Elem]) {
91 for v := range s2.m {
92 s.m[v] = struct{}{}
93 }
94 }
95
96
97
98 func (s Set[Elem]) SubSet(s2 Set[Elem]) {
99 for v := range s2.m {
100 delete(s.m, v)
101 }
102 }
103
104
105
106 func (s Set[Elem]) Intersect(s2 Set[Elem]) {
107 for v := range s.m {
108 if !s2.Contains(v) {
109 delete(s.m, v)
110 }
111 }
112 }
113
114
115 func (s Set[Elem]) Iterate(f func(Elem)) {
116 for v := range s.m {
117 f(v)
118 }
119 }
120
121
122 func (s Set[Elem]) Filter(f func(Elem) bool) {
123 for v := range s.m {
124 if !f(v) {
125 delete(s.m, v)
126 }
127 }
128 }
129
View as plain text