-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy patheither.go
More file actions
108 lines (93 loc) · 2.4 KB
/
Copy patheither.go
File metadata and controls
108 lines (93 loc) · 2.4 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package fn
// Either represents a disjoint union of types L and R. By convention, Left is
// the "primary" or "success" value and Right is the "secondary" or "error"
// value
type Either[L, R any] struct {
isRight bool
left L
right R
}
// NewLeft constructs an Either holding a Left value
func NewLeft[L, R any](l L) Either[L, R] {
return Either[L, R]{left: l}
}
// NewRight constructs an Either holding a Right value
func NewRight[L, R any](r R) Either[L, R] {
return Either[L, R]{isRight: true, right: r}
}
// IsLeft returns true if this Either holds a Left value
func (e Either[L, R]) IsLeft() bool {
return !e.isRight
}
// IsRight returns true if this Either holds a Right value
func (e Either[L, R]) IsRight() bool {
return e.isRight
}
// WhenLeft calls f with the Left value if present
func (e Either[L, R]) WhenLeft(f func(L)) {
if !e.isRight {
f(e.left)
}
}
// WhenRight calls f with the Right value if present
func (e Either[L, R]) WhenRight(f func(R)) {
if e.isRight {
f(e.right)
}
}
// LeftToSome returns Some(left) if Left, None otherwise
func (e Either[L, R]) LeftToSome() Option[L] {
if !e.isRight {
return Some(e.left)
}
return None[L]()
}
// RightToSome returns Some(right) if Right, None otherwise
func (e Either[L, R]) RightToSome() Option[R] {
if e.isRight {
return Some(e.right)
}
return None[R]()
}
// UnwrapLeftOr returns the Left value or the given default
func (e Either[L, R]) UnwrapLeftOr(def L) L {
if !e.isRight {
return e.left
}
return def
}
// UnwrapRightOr returns the Right value or the given default
func (e Either[L, R]) UnwrapRightOr(def R) R {
if e.isRight {
return e.right
}
return def
}
// Swap exchanges Left and Right
func (e Either[L, R]) Swap() Either[R, L] {
if e.isRight {
return NewLeft[R, L](e.right)
}
return NewRight[R, L](e.left)
}
// ElimEither folds an Either: applies f to Left or g to Right
func ElimEither[L, R, O any](e Either[L, R], f func(L) O, g func(R) O) O {
if !e.isRight {
return f(e.left)
}
return g(e.right)
}
// MapLeft transforms the Left value of an Either
func MapLeft[L, R, O any](f func(L) O, e Either[L, R]) Either[O, R] {
if !e.isRight {
return NewLeft[O, R](f(e.left))
}
return NewRight[O, R](e.right)
}
// MapRight transforms the Right value of an Either
func MapRight[L, R, O any](f func(R) O, e Either[L, R]) Either[L, O] {
if !e.isRight {
return NewLeft[L, O](e.left)
}
return NewRight[L, O](f(e.right))
}