add generic functional stuff: Maybe
This commit is contained in:
parent
40a94ce350
commit
d3c85de61f
2 changed files with 48 additions and 0 deletions
27
lib/funky/funky.go
Normal file
27
lib/funky/funky.go
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package funky
|
||||||
|
|
||||||
|
type Maybe[V any] interface {
|
||||||
|
IsNothing() bool
|
||||||
|
Value() V
|
||||||
|
}
|
||||||
|
|
||||||
|
type maybe[V any] struct {
|
||||||
|
isNothing bool
|
||||||
|
value V
|
||||||
|
}
|
||||||
|
|
||||||
|
func Nothing[V any]() Maybe[V] {
|
||||||
|
return &maybe[V]{isNothing: true}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Just[V any](v V) Maybe[V] {
|
||||||
|
return &maybe[V]{false, v}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *maybe[V]) IsNothing() bool {
|
||||||
|
return m.isNothing
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *maybe[V]) Value() V {
|
||||||
|
return m.value
|
||||||
|
}
|
21
tests/funky_test.go
Normal file
21
tests/funky_test.go
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
package scopes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
tbase "testing"
|
||||||
|
|
||||||
|
"git.sr.ht/~cco/go-scopes/lib/funky"
|
||||||
|
"git.sr.ht/~cco/go-scopes/testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFunky(tb *tbase.T) {
|
||||||
|
t := testing.SetUp(tb)
|
||||||
|
t.Run("maybe", MaybeTest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func MaybeTest(t *testing.T) {
|
||||||
|
var i0 funky.Maybe[int] = funky.Nothing[int]()
|
||||||
|
t.AssertEqual(i0.IsNothing(), true)
|
||||||
|
var i1 funky.Maybe[int] = funky.Just(3)
|
||||||
|
t.AssertEqual(i1.IsNothing(), false)
|
||||||
|
t.AssertEqual(i1.Value(), 3)
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue