Skip to content

Instantly share code, notes, and snippets.

@patrickbucher
Created July 10, 2022 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickbucher/05bb918d7ca6925f61bc9372eae76b7b to your computer and use it in GitHub Desktop.
Save patrickbucher/05bb918d7ca6925f61bc9372eae76b7b to your computer and use it in GitHub Desktop.
package errmonad
type ErrMonad[T any] struct {
Val T
Err error
}
type LiftFunc[T any] func(T) ErrMonad[T]
func Lift[T any](x T) ErrMonad[T] {
return ErrMonad[T]{x, nil}
}
func (m ErrMonad[T]) Flatten() T {
return m.Val
}
func (m ErrMonad[T]) FlatMap(f LiftFunc[T]) ErrMonad[T] {
return f(m.Val)
}
func Compose[T any](fs ...LiftFunc[T]) LiftFunc[T] {
return func(x T) ErrMonad[T] {
var y ErrMonad[T]
for i := len(fs) - 1; i >= 0; i-- {
f := fs[i]
y := f(x)
x = y.Flatten()
}
return y
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment