make thunks better
Signed-off-by: Xe Iaso <me@christine.website>
This commit is contained in:
parent
4f9a6ec6f3
commit
716360786a
6
thunk.go
6
thunk.go
|
@ -15,17 +15,17 @@ package gonads
|
||||||
// In this example, `addTwo` is a thunk that contains a partially applied addCurr
|
// In this example, `addTwo` is a thunk that contains a partially applied addCurr
|
||||||
// invocation.
|
// invocation.
|
||||||
type Thunk[T any] struct {
|
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
|
o Option[T] // cache for complete thunk data
|
||||||
}
|
}
|
||||||
|
|
||||||
// Force evaluates a Thunk's action if it needs to, otherwise it returns the
|
// Force evaluates a Thunk's action if it needs to, otherwise it returns the
|
||||||
// previously evaluated result.
|
// previously evaluated result.
|
||||||
func (t Thunk[T]) Force(inp T) T {
|
func (t Thunk[T]) Force() T {
|
||||||
if t.o.IsSome() {
|
if t.o.IsSome() {
|
||||||
return t.o.Yank()
|
return t.o.Yank()
|
||||||
}
|
}
|
||||||
|
|
||||||
t.o.Set(t.doer(inp))
|
t.o.Set(t.doer())
|
||||||
return t.o.Yank()
|
return t.o.Yank()
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,13 +20,18 @@ func TestThunkFib(t *testing.T) {
|
||||||
cache[0].o.Set(0)
|
cache[0].o.Set(0)
|
||||||
cache[1].o.Set(1)
|
cache[1].o.Set(1)
|
||||||
|
|
||||||
fib := func(n int) int {
|
var fib func(int) int
|
||||||
return cache[n-1].Force(n-1) + cache[n-2].Force(n-2)
|
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 {
|
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())
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue