1
0
mirror of https://github.com/IBM/fp-go.git synced 2025-08-10 22:31:32 +02:00

fix: add missing Memoize to readers

Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
Dr. Carsten Leue
2023-09-20 15:56:02 +02:00
parent 44c8441b07
commit 943ae8e009
8 changed files with 75 additions and 2 deletions

View File

@@ -16,6 +16,8 @@
package generic
import (
"sync"
F "github.com/IBM/fp-go/function"
FR "github.com/IBM/fp-go/internal/fromreader"
"github.com/IBM/fp-go/internal/readert"
@@ -99,3 +101,26 @@ func Defer[GEA ~func(E) GA, GA ~func() A, E, A any](gen func() GEA) GEA {
}
}
}
// Memoize computes the value of the provided reader monad lazily but exactly once
// The context used to compute the value is the context of the first call, so do not use this
// method if the value has a functional dependency on the content of the context
func Memoize[GEA ~func(E) GA, GA ~func() A, E, A any](rdr GEA) GEA {
// synchronization primitives
var once sync.Once
var result A
// callback
gen := func(e E) func() {
return func() {
result = rdr(e)()
}
}
// returns our memoized wrapper
return func(e E) GA {
io := gen(e)
return func() A {
once.Do(io)
return result
}
}
}