-
Notifications
You must be signed in to change notification settings - Fork 0
/
equality.go
59 lines (49 loc) · 1.33 KB
/
equality.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
package equality
import "strings"
// Equal is an interface for types that provide an Equal method
type Equal[T any] interface {
Equal(other T) bool
}
// Equality models a type class for types with equality
type Equality[T any] interface {
Equal(a, b T) bool
}
// Fun transforms an equality function into an Equality instance
type Fun[T any] func(a, b T) bool
func (f Fun[T]) Equal(a, b T) bool {
return f(a, b)
}
// Default equality on comparable types.
func Default[T comparable]() Equality[T] {
return Fun[T](func(a, b T) bool {
return a == b
})
}
// Natural equality on types that implement the Equal interface.
func Natural[T Equal[T]]() Equality[T] {
return Fun[T](func(a, b T) bool {
return a.Equal(b)
})
}
// Slice equality, given equality for slice elements.
func Slice[T any](e Equality[T]) Equality[[]T] {
return Fun[[]T](func(a, b []T) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !e.Equal(a[i], b[i]) {
return false
}
}
return true
})
}
// SliceNatural is equivalent to Slice(Natural[T]())
func SliceNatural[T Equal[T]]() Equality[[]T] {
return Slice(Natural[T]())
}
// StringIgnoreCase implements equality while treating upper- and lower-case letters as equivalent (using strings.EqualFold)
func StringIgnoreCase() Equality[string] {
return Fun[string](strings.EqualFold)
}