1
0
mirror of https://github.com/IBM/fp-go.git synced 2025-06-23 00:27:49 +02:00
Files
fp-go/either/resource.go
Dr. Carsten Leue b25de3c7c3 doc: fix case
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
2023-07-18 15:57:54 +02:00

30 lines
727 B
Go

package either
import (
F "github.com/IBM/fp-go/function"
)
// 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
return MonadFold(
res,
Left[A, E],
func(a A) Either[E, A] {
return F.Pipe1(
released,
MapTo[E, any](a),
)
})
},
)
}
}