73 lines
1.1 KiB
Go
73 lines
1.1 KiB
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 (sometimes called `Result`)
|
|
|
|
type Either[V any] interface {
|
|
Maybe[V]
|
|
Ok() bool
|
|
Value() V
|
|
Error() error
|
|
}
|
|
|
|
type either[V any] struct {
|
|
ok bool
|
|
value V
|
|
error error
|
|
}
|
|
|
|
func Value[V any](v V) Either[V] {
|
|
return &either[V]{
|
|
ok: true,
|
|
value: v,
|
|
}
|
|
}
|
|
|
|
func Error[V any](e error) Either[V] {
|
|
return &either[V]{error: e}
|
|
}
|
|
|
|
func (et *either[V]) Ok() bool {
|
|
return et.ok
|
|
}
|
|
|
|
func (et *either[V]) IsNothing() bool {
|
|
return !et.Ok()
|
|
}
|
|
|
|
func (et *either[V]) Value() V {
|
|
return et.value
|
|
}
|
|
|
|
func (et *either[V]) Error() error {
|
|
return et.error
|
|
}
|