-
Notifications
You must be signed in to change notification settings - Fork 7
/
Unifier.go
82 lines (64 loc) · 1.79 KB
/
Unifier.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package values
// Unifier can be used to verify whether a list of values has equal entries.
type Unifier struct {
state unifierState
}
// NewUnifier returns a new instance.
func NewUnifier() Unifier {
return Unifier{state: unifierInitState{}}
}
// Add unifies the given value to the current state.
// The given value must be comparable.
func (u *Unifier) Add(value interface{}) {
u.state = u.state.add(value)
}
// Unified returns the result of the unification.
// If all values that were added to the unifier were equal, then the first
// added value will be returned. Otherwise, nil will be returned.
func (u *Unifier) Unified() interface{} {
return u.state.unified()
}
// IsUnique returns true if the unifier has received only equal values.
func (u Unifier) IsUnique() bool {
return u.state.isUnique()
}
type unifierState interface {
add(value interface{}) unifierState
unified() interface{}
isUnique() bool
}
type unifierInitState struct{}
func (state unifierInitState) add(value interface{}) unifierState {
return unifierMatchedState{value: value}
}
func (state unifierInitState) unified() interface{} {
return nil
}
func (state unifierInitState) isUnique() bool {
return false
}
type unifierMatchedState struct {
value interface{}
}
func (state unifierMatchedState) add(value interface{}) unifierState {
if state.value == value {
return state
}
return unifierMismatchedState{}
}
func (state unifierMatchedState) unified() interface{} {
return state.value
}
func (state unifierMatchedState) isUnique() bool {
return true
}
type unifierMismatchedState struct{}
func (state unifierMismatchedState) add(value interface{}) unifierState {
return state
}
func (state unifierMismatchedState) unified() interface{} {
return nil
}
func (state unifierMismatchedState) isUnique() bool {
return false
}