1
0
mirror of https://github.com/IBM/fp-go.git synced 2025-08-10 22:31:32 +02:00

fix: try a more efficient implementation of standard interfaces

Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
Dr. Carsten Leue
2024-02-07 13:26:17 +01:00
parent d86cf55a3d
commit a774d63e66
3 changed files with 71 additions and 28 deletions

View File

@@ -20,15 +20,17 @@ import (
)
type (
// Either defines a data structure that logically holds either an E or an A. The flag discriminates the cases
Either[E, A any] struct {
either struct {
isLeft bool
value any
}
// Either defines a data structure that logically holds either an E or an A. The flag discriminates the cases
Either[E, A any] either
)
// String prints some debug info for the object
func (s Either[E, A]) String() string {
func eitherString(s *either) string {
if s.isLeft {
return fmt.Sprintf("Left[%T](%v)", s.value, s.value)
}
@@ -36,15 +38,25 @@ func (s Either[E, A]) String() string {
}
// Format prints some debug info for the object
func (s Either[E, A]) Format(f fmt.State, c rune) {
func eitherFormat(e *either, f fmt.State, c rune) {
switch c {
case 's':
fmt.Fprint(f, s.String())
fmt.Fprint(f, eitherString(e))
default:
fmt.Fprint(f, s.String())
fmt.Fprint(f, eitherString(e))
}
}
// String prints some debug info for the object
func (s Either[E, A]) String() string {
return eitherString((*either)(&s))
}
// Format prints some debug info for the object
func (s Either[E, A]) Format(f fmt.State, c rune) {
eitherFormat((*either)(&s), f, c)
}
// IsLeft tests if the [Either] is a left value. Rather use [Fold] if you need to access the values. Inverse is [IsRight].
func IsLeft[E, A any](val Either[E, A]) bool {
return val.isLeft

View File

@@ -17,6 +17,7 @@ package either
import (
"errors"
"fmt"
"testing"
F "github.com/IBM/fp-go/function"
@@ -109,3 +110,13 @@ func TestFromOption(t *testing.T) {
assert.Equal(t, Left[int]("none"), FromOption[int](F.Constant("none"))(O.None[int]()))
assert.Equal(t, Right[string](1), FromOption[int](F.Constant("none"))(O.Some(1)))
}
func TestStringer(t *testing.T) {
e := Of[error]("foo")
exp := "Right[string](foo)"
assert.Equal(t, exp, e.String())
var s fmt.Stringer = e
assert.Equal(t, exp, s.String())
}