1 ! Copyright (C) 2013 Doug Coleman, John Benediktsson.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs combinators combinators.smart fry
4 generalizations kernel macros math quotations sequences locals
5 math.order sequences.generalizations sequences.private
6 stack-checker.transforms system words ;
9 : once ( quot -- ) call ; inline
10 : twice ( quot -- ) dup [ call ] dip call ; inline
11 : thrice ( quot -- ) dup dup [ call ] 2dip [ call ] dip call ; inline
12 : forever ( quot -- ) [ t ] compose loop ; inline
14 MACRO: cond-case ( assoc -- quot )
17 [ first [ dup ] prepose ]
18 [ second [ drop ] prepose ] bi 2array
20 ] map [ cond ] curry ;
22 MACRO: cleave-array ( quots -- quot )
23 [ '[ _ cleave ] ] [ length '[ _ narray ] ] bi compose ;
25 : 3bi* ( u v w x y z p q -- )
26 [ 3dip ] dip call ; inline
28 : 3bi@ ( u v w x y z quot -- )
31 : 4bi ( w x y z p q -- )
32 [ 4keep ] dip call ; inline
34 : 4bi* ( s t u v w x y z p q -- )
35 [ 4dip ] dip call ; inline
37 : 4bi@ ( s t u v w x y z quot -- )
40 : 4tri ( w x y z p q r -- )
41 [ [ 4keep ] dip 4keep ] dip call ; inline
43 : keepd ( ..a x y quot: ( ..a x y -- ..b ) -- ..b x )
46 : plox ( ... x/f quot: ( ... x -- ... ) -- ... )
49 MACRO: smart-plox ( true -- quot )
50 [ inputs [ 1 - [ and ] n*quot ] keep ] keep swap
51 '[ _ _ [ _ ndrop f ] smart-if ] ;
53 : throttle ( quot millis -- quot' )
55 _ nano-count { 0 } 2dup first-unsafe _ + >=
56 [ 0 swap set-nth-unsafe call ] [ 3drop ] if
59 : swap-when ( x y quot: ( x -- n ) quot: ( n n -- ? ) -- x' y' )
60 '[ _ _ 2dup _ bi@ @ [ swap ] when ] call ; inline
63 ! ?1arg-result-falsify
65 : 1falsify ( obj/f -- obj/f ) ; inline
66 : 2falsify ( obj1 obj2 -- obj1/f obj2/f ) 2dup and [ 2drop f f ] unless ; inline
67 : 3falsify ( obj1 obj2 obj3 -- obj1/f obj2/f obj3/f ) 3dup and and [ 3drop f f f ] unless ; inline
69 MACRO: n-and ( n -- quot )
70 1 [-] [ and ] n*quot ;
72 MACRO: n*obj ( n obj -- quot )
75 MACRO:: n-falsify ( n -- quot )
76 [ n ndup n n-and [ n ndrop n f n*obj ] unless ] ;
79 : ?1res ( ..a obj/f quot -- ..b )
82 ! when both args are true, call quot. otherwise dont
83 : ?2res ( ..a obj1 obj2 quot: ( obj1 obj2 -- ? ) -- ..b )
84 [ 2dup and ] dip [ 2drop f ] if ; inline
86 ! try the quot, keep the original arg if quot is true
87 : ?1arg ( obj quot: ( obj -- ? ) -- obj/f )
88 [ ?1res ] 2keep drop '[ _ ] [ f ] if ; inline
90 : ?2arg ( obj1 obj2 quot: ( obj1 obj2 -- ? ) -- obj1/f obj2/f )
91 [ ?2res ] 3keep drop '[ _ _ ] [ f f ] if ; inline
94 : alist>quot* ( default assoc -- quot )
95 [ rot \ if* 3array append [ ] like ] assoc-each ;
97 : cond*>quot ( assoc -- quot )
98 [ dup pair? [ [ drop ] prepend [ t ] swap 2array ] unless ] map
99 reverse! [ no-cond ] swap alist>quot* ;
102 \ cond* [ cond*>quot ] 1 define-transform
103 \ cond* t "no-compile" set-word-prop
106 [ dup callable? [ drop t ] [ first call ] if ] map-find
107 [ dup callable? [ nip call ] [ second call ] if ]