]> gitweb.factorcode.org Git - factor.git/blob - basis/memoize/memoize.factor
merge project-euler.factor
[factor.git] / basis / memoize / memoize.factor
1 ! Copyright (C) 2007, 2009 Slava Pestov, Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel hashtables sequences sequences.private arrays
4 words namespaces make parser math assocs effects definitions
5 quotations summary accessors fry ;
6 IN: memoize
7
8 <PRIVATE
9
10 ! We can't use n*quot, narray and firstn from generalizations because
11 ! they're macros, and macros use memoize!
12 : (n*quot) ( n quot -- quotquot )
13     <repetition> concat >quotation ;
14
15 : [nsequence] ( length exemplar -- quot )
16     [ [ [ 1 - ] keep ] dip '[ _ _ _ new-sequence ] ]
17     [ drop [ [ set-nth-unsafe ] 2keep [ 1 - ] dip ] (n*quot) ] 2bi
18     [ nip ] 3append ; 
19
20 : [firstn] ( length -- quot )
21     [ 0 swap ] swap
22     [ [ nth-unsafe ] 2keep [ 1 + ] dip ] (n*quot)
23     [ 2drop ] 3append ;
24
25 : packer ( seq -- quot )
26     length dup 4 <=
27     [ { [ f ] [ ] [ 2array ] [ 3array ] [ 4array ] } nth ]
28     [ { } [nsequence] ] if ;
29
30 : unpacker ( seq -- quot )
31     length dup 4 <=
32     [ { [ drop ] [ ] [ first2 ] [ first3 ] [ first4 ] } nth ]
33     [ [firstn] ] if ;
34
35 : pack/unpack ( quot effect -- newquot )
36     [ in>> packer ] [ out>> unpacker ] bi surround ;
37
38 : unpack/pack ( quot effect -- newquot )
39     [ in>> unpacker ] [ out>> packer ] bi surround ;
40
41 : make-memoizer ( table quot effect -- quot )
42     [ unpack/pack '[ _ _ cache ] ] keep
43     pack/unpack ;
44
45 PRIVATE>
46
47 : define-memoized ( word quot effect -- )
48     [ drop "memo-quot" set-word-prop ]
49     [ 2drop H{ } clone "memoize" set-word-prop ]
50     [ [ [ dup "memoize" word-prop ] 2dip make-memoizer ] keep define-declared ]
51     3tri ;
52
53 SYNTAX: MEMO: (:) define-memoized ;
54
55 PREDICATE: memoized < word "memoize" word-prop ;
56
57 M: memoized definer drop \ MEMO: \ ; ;
58
59 M: memoized definition "memo-quot" word-prop ;
60
61 M: memoized reset-word
62     [ call-next-method ]
63     [ { "memoize" "memo-quot" } reset-props ]
64     bi ;
65
66 : memoize-quot ( quot effect -- memo-quot )
67     [ H{ } clone ] 2dip make-memoizer ;
68
69 : reset-memoized ( word -- )
70     "memoize" word-prop clear-assoc ;
71
72 : invalidate-memoized ( inputs... word -- )
73     [ stack-effect in>> packer call ] [ "memoize" word-prop delete-at ] bi ;
74
75 \ invalidate-memoized t "no-compile" set-word-prop