1 ! Copyright (C) 2007, 2010 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 effects.parser math assocs effects
5 definitions quotations summary accessors fry hashtables.identity ;
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-as ;
15 : [nsequence] ( length exemplar -- quot )
16 [ [ [ 1 - ] keep ] dip '[ _ _ _ new-sequence ] ]
17 [ drop [ [ set-nth-unsafe ] 2keep [ 1 - ] dip ] (n*quot) ] 2bi
20 : [firstn] ( length -- quot )
22 [ [ nth-unsafe ] 2keep [ 1 + ] dip ] (n*quot)
25 : packer ( seq -- quot )
27 [ { [ f ] [ ] [ 2array ] [ 3array ] [ 4array ] } nth ]
28 [ { } [nsequence] ] if ;
30 : unpacker ( seq -- quot )
32 [ { [ drop ] [ ] [ first2-unsafe ] [ first3-unsafe ] [ first4-unsafe ] } nth ]
35 : pack/unpack ( quot effect -- newquot )
36 [ in>> packer ] [ out>> unpacker ] bi surround ;
38 : unpack/pack ( quot effect -- newquot )
39 [ in>> unpacker ] [ out>> packer ] bi surround ;
41 : make/n ( table quot effect -- quot )
42 [ unpack/pack '[ _ _ cache ] ] keep pack/unpack ;
44 : make/0 ( table quot effect -- quot )
48 [ nip ] [ @ @ [ 0 rot set-nth-unsafe ] keep ] if*
50 ] keep unpacker compose ;
52 : make-memoizer ( table quot effect -- quot )
53 dup in>> length zero? [ make/0 ] [ make/n ] if ;
57 : (define-memoized) ( word quot effect hashtable -- )
58 [ [ drop "memo-quot" set-word-prop ] ] dip
59 '[ 2drop _ "memoize" set-word-prop ]
60 [ [ [ dup "memoize" word-prop ] 2dip make-memoizer ] keep define-declared ]
63 : define-memoized ( word quot effect -- )
64 dup in>> length zero? [ f 1array ] [ H{ } clone ] if
67 : define-identity-memoized ( word quot effect -- )
68 dup in>> length zero? [ f 1array ] [ IH{ } clone ] if
71 SYNTAX: MEMO: (:) define-memoized ;
73 SYNTAX: IDENTITY-MEMO: (:) define-identity-memoized ;
75 PREDICATE: memoized < word "memoize" word-prop >boolean ;
77 M: memoized definer drop \ MEMO: \ ; ;
79 M: memoized definition "memo-quot" word-prop ;
81 M: memoized reset-word
83 [ { "memoize" "memo-quot" } reset-props ]
86 : memoize-quot ( quot effect -- memo-quot )
87 [ H{ } clone ] 2dip make-memoizer ;
89 : reset-memoized ( word -- )
90 "memoize" word-prop dup sequence?
91 [ f swap set-first ] [ clear-assoc ] if ;
93 : invalidate-memoized ( inputs... word -- )
94 [ stack-effect in>> packer call ] [ "memoize" word-prop delete-at ] bi ;
96 \ invalidate-memoized t "no-compile" set-word-prop