2023-07-07 22:31:06 +02:00
|
|
|
package either
|
|
|
|
|
|
|
|
import (
|
2023-07-18 15:57:54 +02:00
|
|
|
F "github.com/IBM/fp-go/function"
|
2023-07-07 22:31:06 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// constructs a function that creates a resource, then operates on it and then releases the resource
|
|
|
|
func WithResource[E, R, A any](onCreate func() Either[E, R], onRelease func(R) Either[E, any]) func(func(R) Either[E, A]) Either[E, A] {
|
|
|
|
|
|
|
|
return func(f func(R) Either[E, A]) Either[E, A] {
|
|
|
|
return MonadChain(
|
|
|
|
onCreate(), func(r R) Either[E, A] {
|
|
|
|
// run the code and make sure to release as quickly as possible
|
|
|
|
res := f(r)
|
|
|
|
released := onRelease(r)
|
|
|
|
// handle the errors
|
2023-07-08 11:21:26 +02:00
|
|
|
return MonadFold(
|
2023-07-07 22:31:06 +02:00
|
|
|
res,
|
2023-07-14 13:20:00 +02:00
|
|
|
Left[A, E],
|
2023-07-07 22:31:06 +02:00
|
|
|
func(a A) Either[E, A] {
|
|
|
|
return F.Pipe1(
|
|
|
|
released,
|
|
|
|
MapTo[E, any](a),
|
|
|
|
)
|
|
|
|
})
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|