-
Notifications
You must be signed in to change notification settings - Fork 12
/
predicate.go
63 lines (52 loc) · 1.48 KB
/
predicate.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
package fuego
// Predicate represents a predicate (boolean-valued function) of one argument.
// Could also be: `type Predicate[T any] Function[T, bool]`.
type Predicate[T any] func(t T) bool
// And is a composed predicate that represents a short-circuiting logical
// AND of this predicate and another.
func (p Predicate[T]) And(other Predicate[T]) Predicate[T] {
return func(t T) bool {
if p == nil || other == nil {
return False[T]()(t)
}
return p(t) && other(t)
}
}
// Or is a composed predicate that represents a short-circuiting logical
// OR of two predicates.
func (p Predicate[T]) Or(other Predicate[T]) Predicate[T] {
return func(t T) bool {
if p == nil {
p = False[T]()
}
if other == nil {
return p(t)
}
return p(t) || other(t)
}
}
// Xor is a composed predicate that represents a short-circuiting logical
// XOR of two predicates.
func (p Predicate[T]) Xor(other Predicate[T]) Predicate[T] {
return func(t T) bool {
return p.Or(other).And(p.And(other).Negate())(t)
}
}
// Negate is an alias for Not().
func (p Predicate[T]) Negate() Predicate[T] {
return p.Not()
}
// Not is the logical negation of a predicate.
func (p Predicate[T]) Not() Predicate[T] {
return func(t T) bool {
return p == nil || !p(t)
}
}
// False returns a predicate that returns always false.
func False[T any]() Predicate[T] {
return func(T) bool { return false }
}
// True returns a predicate that returns always true.
func True[T any]() Predicate[T] {
return False[T]().Negate()
}