68 lines
1,011 B
Go
68 lines
1,011 B
Go
// Package funky provides a few constructs usually present in pure
|
|
// functional programming environments, using Go 1.18 generics.
|
|
package funky
|
|
|
|
// Maybe (sometimes called `Option`)
|
|
|
|
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
|
|
}
|
|
|
|
// 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
|
|
}
|