Created
July 10, 2022 12:33
-
-
Save patrickbucher/05bb918d7ca6925f61bc9372eae76b7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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