add new funky type

This commit is contained in:
Helmut Merz 2023-07-17 19:45:48 +02:00
parent de6535a273
commit c54562b998
2 changed files with 48 additions and 0 deletions

View file

@ -29,3 +29,40 @@ func (m *maybe[V]) IsNothing() bool {
func (m *maybe[V]) Value() V {
return m.value
}
// Either
type Either[V any] interface {
Ok() bool
Right() V
Left() error
}
type either[V any] struct {
ok bool
right V
left error
}
func Right[V any](v V) Either[V] {
return &either[V]{
ok: true,
right: v,
}
}
func Left[V any](e error) Either[V] {
return &either[V]{left: e}
}
func (et *either[V]) Ok() bool {
return et.ok
}
func (et *either[V]) Right() V {
return et.right
}
func (et *either[V]) Left() error {
return et.left
}

View file

@ -1,6 +1,7 @@
package scopes_test
import (
"fmt"
tbase "testing"
"git.sr.ht/~cco/go-scopes/lib/funky"
@ -10,6 +11,7 @@ import (
func TestFunky(tb *tbase.T) {
t := testing.SetUp(tb)
t.Run("maybe", MaybeTest)
t.Run("either", EitherTest)
t.Run("iterator", IteratorTest)
}
@ -21,6 +23,15 @@ func MaybeTest(t *testing.T) {
t.AssertEqual(i1.Value(), 3)
}
func EitherTest(t *testing.T) {
var e0 funky.Either[int] = funky.Right[int](7)
t.AssertEqual(e0.Ok(), true)
t.AssertEqual(e0.Right(), 7)
var e1 funky.Either[int] = funky.Left[int](fmt.Errorf("Some Error"))
t.AssertEqual(e1.Ok(), false)
t.AssertEqual(fmt.Sprint(e1.Left()), "Some Error")
}
func IteratorTest(t *testing.T) {
sl := []int{3, 4, 5}
var it funky.Iterator[int] = funky.SliceIterator[int](sl)