Skip to content

Commit

Permalink
memoize: fix a few more zero input cases
Browse files Browse the repository at this point in the history
  • Loading branch information
mrjbq7 committed Apr 5, 2023
1 parent d362b56 commit a937766
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
15 changes: 15 additions & 0 deletions core/memoize/memoize-tests.factor
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,18 @@ MEMO: bar ( -- x ) bar-counter counter ;
bar
bar
] unit-test

SYMBOL: baz-counter
0 baz-counter set-global

MEMO: baz ( -- x ) baz-counter counter drop f ;

{ 0 f 1 f 1 f 1 } [
baz-counter get-global
baz
baz-counter get-global
baz
baz-counter get-global
baz
baz-counter get-global
] unit-test
18 changes: 9 additions & 9 deletions core/memoize/memoize.factor
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ IN: memoize

: packer ( seq -- quot )
length dup 4 <=
[ { [ t ] [ ] [ 2array ] [ 3array ] [ 4array ] } nth ]
[ { [ f ] [ ] [ 2array ] [ 3array ] [ 4array ] } nth ]
[ { } [nsequence] ] if ;

: unpacker ( seq -- quot )
Expand All @@ -44,9 +44,9 @@ IN: memoize
: make/0 ( table quot effect -- quot )
out>> [
packer '[
_
[ first-unsafe ]
[ @ @ [ 0 rot set-nth-unsafe ] keep ] ?unless
_ dup first-unsafe dup null eq? [
drop @ @ [ 0 rot set-nth-unsafe ] keep
] [ nip ] if
]
] keep unpacker compose ;

Expand All @@ -62,11 +62,11 @@ PRIVATE>
3tri ;

: define-memoized ( word quot effect -- )
dup in>> length zero? [ f 1array ] [ H{ } clone ] if
dup in>> length zero? [ null 1array ] [ H{ } clone ] if
(define-memoized) ;

: define-identity-memoized ( word quot effect -- )
dup in>> length zero? [ f 1array ] [ IH{ } clone ] if
dup in>> length zero? [ null 1array ] [ IH{ } clone ] if
(define-memoized) ;

PREDICATE: memoized < word "memoize" word-prop >boolean ;
Expand All @@ -83,18 +83,18 @@ M: memoized reset-word
bi ;

: memoize-quot ( quot effect -- memo-quot )
dup in>> length zero? [ f 1array ] [ H{ } clone ] if
dup in>> length zero? [ null 1array ] [ H{ } clone ] if
-rot make-memoizer ;

: reset-memoized ( word -- )
"memoize" word-prop dup sequence?
[ f swap set-first ] [ clear-assoc ] if ;
[ null swap set-first ] [ clear-assoc ] if ;

: invalidate-memoized ( inputs... word -- )
[ stack-effect in>> packer call ]
[
"memoize" word-prop dup sequence?
[ f swap set-first ] [ delete-at ] if
[ null swap set-first ] [ delete-at ] if
]
bi ;

Expand Down

0 comments on commit a937766

Please sign in to comment.