From 716360786ae4fa6429bd6e73f09de5934d8984c2 Mon Sep 17 00:00:00 2001 From: Xe Iaso Date: Sun, 24 Apr 2022 23:33:59 +0000 Subject: [PATCH] make thunks better Signed-off-by: Xe Iaso --- thunk.go | 6 +++--- thunk_test.go | 13 +++++++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/thunk.go b/thunk.go index 6a9c97e..ca24455 100644 --- a/thunk.go +++ b/thunk.go @@ -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() } diff --git a/thunk_test.go b/thunk_test.go index 3014dfa..48eb3f9 100644 --- a/thunk_test.go +++ b/thunk_test.go @@ -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()) }