Skip to content

Commit ff8eff4

Browse files
Roasbeefguggero
authored andcommitted
fn: add new Either[L, R] type
1 parent ea8d35b commit ff8eff4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

fn/either.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package fn
2+
3+
// Either is a type that can be either left or right.
4+
type Either[L any, R any] struct {
5+
left Option[L]
6+
right Option[R]
7+
}
8+
9+
// NewLeft returns an Either with a left value.
10+
func NewLeft[L any, R any](l L) Either[L, R] {
11+
return Either[L, R]{left: Some(l), right: None[R]()}
12+
}
13+
14+
// NewRight returns an Either with a right value.
15+
func NewRight[L any, R any](r R) Either[L, R] {
16+
return Either[L, R]{left: None[L](), right: Some(r)}
17+
}
18+
19+
// WhenLeft executes the given function if the Either is left.
20+
func (e Either[L, R]) WhenLeft(f func(L)) {
21+
e.left.WhenSome(f)
22+
}
23+
24+
// WhenRight executes the given function if the Either is right.
25+
func (e Either[L, R]) WhenRight(f func(R)) {
26+
e.right.WhenSome(f)
27+
}
28+
29+
// IsLeft returns true if the Either is left.
30+
func (e Either[L, R]) IsLeft() bool {
31+
return e.left.IsSome()
32+
}
33+
34+
// IsRight returns true if the Either is right.
35+
func (e Either[L, R]) IsRight() bool {
36+
return e.right.IsSome()
37+
}

0 commit comments

Comments
 (0)