2023-07-08 11:21:26 +02:00
|
|
|
package either
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
2023-07-09 10:21:56 +02:00
|
|
|
// Either defines a data structure that logically holds either an E or an A. The flag discriminates the cases
|
|
|
|
type (
|
|
|
|
Either[E, A any] struct {
|
|
|
|
isLeft bool
|
|
|
|
left E
|
|
|
|
right A
|
|
|
|
}
|
2023-07-08 11:21:26 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// String prints some debug info for the object
|
|
|
|
func (s Either[E, A]) String() string {
|
2023-07-09 10:21:56 +02:00
|
|
|
if s.isLeft {
|
|
|
|
return fmt.Sprintf("Left[%T, %T](%v)", s.left, s.right, s.left)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
2023-07-09 10:21:56 +02:00
|
|
|
return fmt.Sprintf("Right[%T, %T](%v)", s.left, s.right, s.right)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Format prints some debug info for the object
|
|
|
|
func (s Either[E, A]) Format(f fmt.State, c rune) {
|
|
|
|
switch c {
|
|
|
|
case 's':
|
|
|
|
fmt.Fprint(f, s.String())
|
|
|
|
default:
|
|
|
|
fmt.Fprint(f, s.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsLeft[E, A any](val Either[E, A]) bool {
|
2023-07-09 10:21:56 +02:00
|
|
|
return val.isLeft
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func IsRight[E, A any](val Either[E, A]) bool {
|
2023-07-09 10:21:56 +02:00
|
|
|
return !val.isLeft
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Left[E, A any](value E) Either[E, A] {
|
2023-07-09 10:21:56 +02:00
|
|
|
return Either[E, A]{isLeft: true, left: value}
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Right[E, A any](value A) Either[E, A] {
|
2023-07-09 10:21:56 +02:00
|
|
|
return Either[E, A]{isLeft: false, right: value}
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func MonadFold[E, A, B any](ma Either[E, A], onLeft func(e E) B, onRight func(a A) B) B {
|
|
|
|
if IsLeft(ma) {
|
|
|
|
return onLeft(ma.left)
|
|
|
|
}
|
|
|
|
return onRight(ma.right)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Unwrap[E, A any](ma Either[E, A]) (A, E) {
|
|
|
|
return ma.right, ma.left
|
|
|
|
}
|