make thunks better

Signed-off-by: Xe Iaso <me@christine.website>
This commit is contained in:
Cadey Ratio 2022-04-24 23:33:59 +00:00
parent 4f9a6ec6f3
commit 716360786a
2 changed files with 12 additions and 7 deletions

View File

@ -15,17 +15,17 @@ package gonads
// In this example, `addTwo` is a thunk that contains a partially applied addCurr
// invocation.
type Thunk[T any] struct {
doer func(T) T // action being thunked
doer func() T // action being thunked
o Option[T] // cache for complete thunk data
}
// Force evaluates a Thunk's action if it needs to, otherwise it returns the
// previously evaluated result.
func (t Thunk[T]) Force(inp T) T {
func (t Thunk[T]) Force() T {
if t.o.IsSome() {
return t.o.Yank()
}
t.o.Set(t.doer(inp))
t.o.Set(t.doer())
return t.o.Yank()
}

View File

@ -20,13 +20,18 @@ func TestThunkFib(t *testing.T) {
cache[0].o.Set(0)
cache[1].o.Set(1)
fib := func(n int) int {
return cache[n-1].Force(n-1) + cache[n-2].Force(n-2)
var fib func(int) int
fib = func(n int) int {
if cache[n].o.IsSome() {
return *cache[n].o.val
}
return fib(n-1) + fib(n-2)
}
for i := range cache {
cache[i].doer = fib
i := i
cache[i].doer = func() int { return fib(i) }
}
t.Log(cache[40].Force(40))
t.Log(cache[40].Force())
}