1 ! Copyright (C) 2007, 2008 Daniel Ehrenberg, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: sequences kernel strings math fry ;
6 ! All traversal goes in postorder
8 GENERIC: branch? ( object -- ? )
10 M: sequence branch? drop t ;
11 M: integer branch? drop f ;
12 M: string branch? drop f ;
13 M: object branch? drop f ;
15 : deep-each ( obj quot: ( elt -- ) -- )
16 [ call ] 2keep over branch?
17 [ '[ _ deep-each ] each ] [ 2drop ] if ; inline recursive
19 : deep-map ( obj quot: ( elt -- elt' ) -- newobj )
20 [ call ] keep over branch?
21 [ '[ _ deep-map ] map ] [ drop ] if ; inline recursive
23 : deep-filter ( obj quot: ( elt -- ? ) -- seq )
24 over [ pusher [ deep-each ] dip ] dip
25 dup branch? [ like ] [ drop ] if ; inline recursive
27 : (deep-find) ( obj quot: ( elt -- ? ) -- elt ? )
28 [ call ] 2keep rot [ drop t ] [
30 [ f ] 2dip '[ nip _ (deep-find) ] find drop >boolean
32 ] if ; inline recursive
34 : deep-find ( obj quot -- elt ) (deep-find) drop ; inline
36 : deep-contains? ( obj quot -- ? ) (deep-find) nip ; inline
38 : deep-all? ( obj quot -- ? )
39 '[ @ not ] deep-contains? not ; inline
41 : deep-member? ( obj seq -- ? )
43 _ swap dup branch? [ member? ] [ 2drop f ] if
44 ] deep-find >boolean ;
46 : deep-subseq? ( subseq seq -- ? )
48 _ swap dup branch? [ subseq? ] [ 2drop f ] if
49 ] deep-find >boolean ;
51 : deep-change-each ( obj quot: ( elt -- elt' ) -- )
53 '[ _ [ call ] keep over [ deep-change-each ] dip ] change-each
54 ] [ 2drop ] if ; inline recursive
56 : flatten ( obj -- seq )
57 [ branch? not ] deep-filter ;