1 ! Copyright (C) 2007, 2009 Chris Double, Doug Coleman, Eduardo
2 ! Cavazos, Slava Pestov.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: arrays combinators kernel kernel.private math math.ranges
5 memoize.private sequences ;
8 ! These words can be inline combinators the word does no math on
9 ! the input parameters, e.g. n.
10 ! If math is done, the word needs to be a macro so the math can
11 ! be done at compile-time.
14 ALIAS: n*quot (n*quot)
16 MACRO: call-n ( n -- quot )
17 [ call ] <repetition> '[ _ cleave ] ;
19 : repeat ( n obj quot -- ) swapd times ; inline
23 MACRO: nsum ( n -- quot )
26 ERROR: nonpositive-npick n ;
28 MACRO: npick ( n -- quot )
30 { [ dup 0 <= ] [ nonpositive-npick ] }
31 { [ dup 1 = ] [ drop [ dup ] ] }
32 [ 1 - [ dup ] [ '[ _ dip swap ] ] repeat ]
35 MACRO: nover ( n -- quot )
36 dup 1 + '[ _ npick ] n*quot ;
39 [ '[ _ npick ] ] keep call-n ; inline
41 MACRO: dupn ( n -- quot )
43 [ 1 - [ dup ] n*quot ] if-zero ;
45 MACRO: nrot ( n -- quot )
46 1 - [ ] [ '[ _ dip swap ] ] repeat ;
48 MACRO: -nrot ( n -- quot )
49 1 - [ ] [ '[ swap _ dip ] ] repeat ;
52 [ drop ] swap call-n ; inline
55 '[ _ ndrop ] dip ; inline
58 [ [ dip ] curry ] swap call-n call ; inline
61 dup '[ [ _ ndup ] dip _ ndip ] call ; inline
64 [ curry ] swap call-n ; inline
67 [ with ] swap call-n ; inline
69 : nbi ( quot1 quot2 n -- )
70 [ nip nkeep ] [ drop nip call ] 3bi ; inline
72 MACRO: ncleave ( quots n -- quot )
73 [ '[ _ '[ _ _ nkeep ] ] map [ ] join ] [ '[ _ ndrop ] ] bi
76 MACRO: nspread ( quots n -- quot )
77 over empty? [ 2drop [ ] ] [
81 '[ [ _ _ nspread ] _ ndip @ ]
84 MACRO: spread* ( n -- quot )
86 [1..b) [ '[ [ [ _ ndip ] curry ] dip compose ] ] map [ ] concat-as
90 MACRO: nspread* ( m n -- quot )
92 [ * 0 ] [ drop neg ] 2bi
93 <range> rest >array dup length <iota> <reversed>
94 [ '[ [ [ _ ndip ] curry ] _ ndip ] ] 2map
96 [ length 1 - [ compose ] <array> concat append ] bi
100 MACRO: cleave* ( n -- quot )
102 [ 1 - [ [ [ keep ] curry ] dip compose ] n*quot [ call ] compose ]
105 : napply ( quot n -- )
106 [ dupn ] [ spread* ] bi ; inline
108 : mnapply ( quot m n -- )
109 [ nip dupn ] [ nspread* ] 2bi ; inline
111 : apply-curry ( a... quot n -- )
112 [ currier ] dip napply ; inline
114 : cleave-curry ( a quot... n -- )
115 [ currier ] swap [ napply ] [ cleave* ] bi ; inline
117 : spread-curry ( a... quot... n -- )
118 [ currier ] swap [ napply ] [ spread* ] bi ; inline
120 MACRO: mnswap ( m n -- quot )
121 1 + '[ _ -nrot ] swap '[ _ _ napply ] ;
123 MACRO: nweave ( n -- quot )
124 [ dup <iota> <reversed> [ '[ _ _ mnswap ] ] with map ] keep
128 [ bi-curry ] swap call-n ; inline
130 MACRO: map-compose ( quots quot -- quot' )
131 '[ _ compose ] map '[ _ ] ;