Skip to content

Commit

Permalink
Improve evector (#1087)
Browse files Browse the repository at this point in the history
Add an optional init: argument to memoize-recursive-sequence to cover
the usual case when users don't care to use list->evector.
  • Loading branch information
fare authored Dec 10, 2023
1 parent ab87641 commit 50d47fc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
14 changes: 11 additions & 3 deletions doc/reference/std/misc/evector.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,12 @@ if the fill-pointer could be incremented, set the value at last index to `x`.

### memoize-recursive-sequence
```scheme
(memoize-recursive-sequence fun cache: (cache (list->evector '())))
(memoize-recursive-sequence fun init: (init '()) cache: (cache (list->evector init))) => function
```
Define a function `f` from a non-negative fixnum `n`
that caches its initial values in an extensible vector `cache`.
that caches its initial values (zero-based) in extensible vector `cache`,
that by default is initialized from list `init`, that defaults to the empty list.

The function body `fun` may make recursive calls to the outer function `f`
with strictly lower values of the integer argument `n`;
the `cache` can be initialized with the initial values for `f`;
Expand All @@ -183,9 +185,15 @@ entries filled after `fun` returns.
```scheme
> (def fibonacci
(memoize-recursive-sequence (λ (n) (+ (fibonacci (- n 1)) (fibonacci (- n 2))))
cache: (list->evector '(0 1))))
init: '(0 1)))
> (fibonacci 8)
21
> (def fact-e (list->evector '(1)))
> (def fact (memoize-recursive-sequence (λ (n) (* n (fact (1- n)))) cache: fact-e))
> (fact 7)
5040
> (subvector (evector->vector fact-e) 3 8)
#(6 24 120 720 5040)
```
:::

Expand Down
4 changes: 3 additions & 1 deletion src/std/misc/evector.ss
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@
(vector->list (&evector->vector e)))

;;; memoize the start of a recursively defined sequence
(def (memoize-recursive-sequence fun cache: (cache (list->evector '())))
(def (memoize-recursive-sequence fun
init: (init '())
cache: (cache (list->evector init)))
(check-argument-procedure fun)
(check-argument-evector cache)
(lambda (n)
Expand Down

0 comments on commit 50d47fc

Please sign in to comment.